【问题标题】:Binding List to a ComboBox将列表绑定到组合框
【发布时间】:2014-03-16 22:53:12
【问题描述】:

我想将我的列表绑定到一个组合框:

 private BindingList<Tool> toolList = new BindingList<Tool>();

XAML 绑定:

  <ComboBox ItemsSource="{Binding toolList}" DisplayMemberPath="Name" 
   SelectedValuePath="Name" SelectedValue= "{Binding toolList}"   Height="22" 
   Name="comboBoxTools" Width="185" SelectionChanged="comboBoxTools_SelectionChanged" />

列表的对象具有成员名称和路径,我希望名称出现在组合框中。 当我将新对象添加到列表时,它不会出现在组合框中:

  private void buttonAdd_Click(object sender, RoutedEventArgs e)
    {
        InputDialog input = new InputDialog();
        input.ShowDialog();
        inputNewTool = input.enteredTxt;

        if (inputNewTool != null)
        {
            System.Windows.Forms.MessageBox.Show("Chose the Tool's directory");
            dlg.DefaultExt = ".exe";
            dlg.Filter = "Application (.exe)|*.exe";

            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Tool tool = new Tool();
                tool.Name = inputNewTool;
                tool.Path = dlg.FileName;
                toolList.Add(tool);
                //comboBoxTools.Items.Add(tool);
            }                
       }            
     }

现在使用 ObservableCollection:

public ObservableCollection<Tool> toolList = new ObservableCollection<Tool>();
  private void buttonAdd_Click(object sender, RoutedEventArgs e)
    {
        InputDialog input = new InputDialog();
        input.ShowDialog();
        inputNewTool = input.enteredTxt;

        if (inputNewTool != null)
        {
            System.Windows.Forms.MessageBox.Show("Chose the Tool's directory");
            dlg.DefaultExt = ".exe";
            dlg.Filter = "Application (.exe)|*.exe";

            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Tool tool = new Tool();
                tool.Name = inputNewTool;
                tool.Path = dlg.FileName;
                toolList.Add(tool);
                //comboBoxTools.Items.Add(tool);
            }                
       }            
     }

XAML 绑定:

<ComboBox ItemsSource="{Binding Path=toolList}" DisplayMemberPath="Name" 
SelectedValuePath="Name" SelectedValue= "{Binding Path=toolList}"   Height="22" 
Name="comboBoxTools" Width="185" SelectionChanged="comboBoxTools_SelectionChanged" />

【问题讨论】:

  • 尝试使用 BindingList 和 ObservableCollection
  • 我将 List 替换为 ObservableCollection 并且没有任何改变:(
  • 你知道你需要一个公共属性来绑定吗?
  • 当我将 toolList 的属性更改为公共时,它无济于事
  • 显示您的代码。你有得到吗?

标签: wpf data-binding combobox


【解决方案1】:
public ObservableCollection<Tool> ToolList 
{
   get { return toolList; }
}

【讨论】:

  • 谢谢我完成了,但问题没有解决:(。绑定没有实现
  • 您是否将绑定更改为 ToolList?
  • 实际 XAMl 代码:
  • 取出 DataContext="{Binding}" 并在 ctor 第一行添加 this.DataContext = this;
  • 在 MainWindow 的构造函数中我必须添加这个?
猜你喜欢
  • 1970-01-01
  • 2016-04-23
  • 2018-06-20
  • 2010-10-10
  • 2011-06-28
  • 2018-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多