WPF ListBox 的 DisplayMemberPath 和 SelectedValuePath

3

如何使用Linq To Sql将值和键绑定到列表框?

我正在使用Linq to Sql类填充列表框,以下是WPF代码:

<ListBox  Name="listBox1" Loaded="listBox1_Loaded" />

以下显示了FullName,但不包括Case_Number:
using (ToolboxDataContext toolboxDB = new ToolboxDataContext())
{
    var x = toolboxDB.DropDownIndividuals().ToList(); 
    listBox1.ItemsSource = x;
}

我也尝试过这个方法,但没有成功:
foreach (var y in x)
{
    listBox1.DisplayMemberPath = y.FullName.ToString() ;
    listBox1.SelectedValuePath = y.Case_Number.ToString() ;
    // Console.WriteLine(y.Case_Number.ToString());
}
2个回答

7
在标记中,您可以指定要绑定的类型,例如:
<ListBox DisplayMemberPath="FullName" SelectedValuePath="Case_Number"/>

太好了。现在我的代码private void listBox1_SelectionChanged_1(object sender, SelectionChangedEventArgs e) { Console.WriteLine(listBox1.SelectedValue.ToString()); }可以正常工作了! - hidden

0

好的,

在XAML中:

<ListBox x:Name="listBox1" 
         DisplayMemberPath="FullName" 
         SelectedValuePath="Case_Number" />

在代码后台:

using (ToolboxDataContext toolboxDB = new ToolboxDataContext())
     PersonsListBox.ItemsSource = toolboxDB.DropDownIndividuals().ToList(); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接