将列表绑定到ComboBox

时间:2014-02-17 15:09:23

标签: wpf data-binding combobox

我想将我的列表绑定到一个comboBox:

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

XAML-Binding:

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

列表的对象具有成员名称和路径,我希望名称出现在comboBox中。 当我向List添加一个新的Object时,它不会出现在ComboBox中:

  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" />

1 个答案:

答案 0 :(得分:1)

public ObservableCollection<Tool> ToolList 
{
   get { return toolList; }
}