-
19-08-2019 - |
题
我想有一个用户控件,将他们的集合(财产“数据”),并将其显示在列表框中。 当我运行我的应用程序没有任何显示在列表框中。能否请您指出我做错了什么? 感谢!!!
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public override string ToString()
{
return Name + "(" + Age + ")";
}
}
用户控制: (uc1.xaml.cs)
public partial class uc1
{
public static readonly DependencyProperty DataProperty = DependencyProperty.Register("Data", typeof (List<Person>), typeof (uc1));
public List<Person> Data
{
get { return (List<Person>) GetValue(DataProperty); }
set { SetValue(DataProperty, value); }
}
public uc1()
{
InitializeComponent();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
DataContext = Data;
}
}
(uc1.xaml)
<ListBox ItemsSource="{Binding Name}" />
解决方案
在ItemsSource属性控制着显示在列表框的项列表。如果你想在列表框来显示每个人一条线,你需要设置的ItemsSource直接绑定到DataContext。然后您使用的DisplayMemberPath属性来控制,以显示该人类的属性。
下面是我的示例代码,对我的作品。 人类是相同的。
在Window1.xaml.cs:
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
List<Person> Data = new List<Person>();
Data.Add(new Person { Name = "Test 1", Age = 5 });
Data.Add(new Person { Name = "Test 2", Age = 10 });
this.DataContext = Data;
}
}
在Window1.xaml
<ListBox ItemsSource="{Binding}" DisplayMemberPath="Name" />
不隶属于 StackOverflow