【问题标题】:WPF User ControlWPF 用户控件
【发布时间】:2010-10-01 16:17:20
【问题描述】:

我想要一个用户控件,它接受一组人员(属性“数据”)并将它们显示在列表框中。 当我运行我的应用程序时,列表框中没有显示任何内容。你能指出我做错了什么吗? 谢谢!!!

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

【问题讨论】:

    标签: wpf data-binding user-controls dependency-properties


    【解决方案1】:

    ItemsSource 属性控制在列表框中显示的项目列表。如果希望 ListBox 为每个人显示一行,则需要将 ItemsSource 设置为直接绑定到 DataContext。然后使用 DisplayMemberPath 属性来控制要显示的 Person 类的哪个属性。

    这是适用于我的示例代码。 person 类是一样的。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-27
      • 1970-01-01
      • 1970-01-01
      • 2020-06-28
      • 2010-09-23
      • 1970-01-01
      • 2011-03-21
      相关资源
      最近更新 更多