Ada*_*dam 2 wpf binding wpf-controls
我做错了什么......你知道它是怎么回事.
我试过使用ItemsSource,DataContext,DisplayMemberPath和SelectedValuePath,我得到一个空白的列表,列出了在Person对象中调用的ToString方法;
真正需要帮助的是某人发布适用于此示例的答案.
我已经简化了问题,因为我在使用数据绑定泛型方面遇到了困难.
我创建了一个简单的通用人员列表,并希望将其绑定到组合.(也想尝试使用ListView).
我得到一个空格列表或'xxxx.Person'列表,其中xxxx =名称空间
<Window x:Class="BindingGenerics.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="300" Width="300">
<Grid>
<ComboBox Name="ComboBox1"
ItemsSource="{Binding}"
Height="50"
DisplayMemberPath="Name"
SelectedValuePath="ID"
FontSize="14"
VerticalAlignment="Top">
</ComboBox>
</Grid>
</Window>
using System.Windows;
using System.ComponentModel;
namespace BindingGenerics
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Person p = new Person();
// I have tried List and BindingList
//List<Person> list = new List<Person>();
BindingList<Person> list = new BindingList<Person>();
p.Name = "aaaa";
p.ID = "1111";
list.Add(p);
p = new Person();
p.Name = "bbbb";
p.ID = "2222";
list.Add(p);
p = new Person();
p.Name = "cccc";
p.ID = "3333";
list.Add(p);
p = new Person();
p.Name = "dddd";
p.ID = "4444";
list.Add(p);
ComboBox1.DataContext = list;
}
}
public struct Person
{
public string Name;
public string ID;
}
}
Run Code Online (Sandbox Code Playgroud)
在您的代码示例中,Person.Name是一个字段而不是一个属性.WPF数据绑定仅考虑属性,而不考虑字段,因此您需要将Person.Name更改为属性.
将您的人员声明更改为:
public class Person
{
public string Name { get; set; }
public string ID { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
(对于生产代码,您可能希望使用an ObservableCollection<Person>而不是a List<Person>,并使Person不可变或使其实现INotifyPropertyChanged - 但这些不是您当前问题的根源.)