【发布时间】:2014-02-18 13:08:59
【问题描述】:
我创建 ObservableCollection:
public ObservableCollection<Tool> toolList = new ObservableCollection<Tool>();
我在构造函数中设置了 DataContext:
public MainWindow()
{
InitializeComponent();
DataContext = toolList;
}
实际:
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
公开列表:
public ObservableCollection<Tool> ToolList
{
get { return toolList; }
}
如何将对象添加到列表中:
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);
}
}
}
我希望只有工具对象的名称显示在组合框中。 XAML:
<ComboBox ItemsSource="{Binding Path= ToolList}" DisplayMemberPath="Name"
SelectedValuePath ="Name" SelectedValue="{Binding Path=ToolList}" Height="22"
Name="comboBoxTools" Width="185" IsEditable="False" />
编辑:现在 xaml 显示如下:
<ComboBox ItemsSource="{Binding Path= ToolList,
UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="Name"
工具类:
public class Tool
{
public string Name { get; set; }
public string Path { get; set; }
public Tool() { }
}
我在组合框中看不到任何东西。为什么?这些工具已成功添加到集合中。 我生气了
【问题讨论】:
-
您的
SelectedValue绑定到与您的ItemsSource相同的路径。这看起来很可疑。 -
我删除了选定的值和选定的路径,但这并没有解决问题:/
标签: c# wpf observablecollection