首页 > 解决方案 > 如何将类的属性列表绑定到一系列标签

问题描述

所以,搜索没有帮助,我对绑定世界有点陌生。

尽可能简化它:我有 2 个窗口和一个类。在第一个窗口中,我在全球范围内声明了我的班级列表:List<MyClass> MyList = new List<MyClass>();

该类支持使用 PropertyChanged.Fody Nuget 包的 INotifyPropertyChanged。

class MyClass : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public string FirstName { get; set; }
    }

在第一个窗口中,我有一个文本框和一个按钮。当我按下按钮时,具有 TextBox.Text 的 FirstName 属性的新 MyClass 将添加到 MyList。然后将一个新行添加到第二个窗口的主网格,并将一个标签添加到新行:

private void Button_Click(object sender, RoutedEventArgs e)
{
    MyClass mc = new MyClass() { FirstName = TextBox.Text; };
    MyList.Add(mc);

    //find my second window and add row and label to its grid
    foreach (Window window in Application.Current.Windows)
    {
        if (window.GetType() == typeof(SecondWindow))
        {
            Grid mgrid = (window as SecondWindow).MainGrid;
            mgrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

            Label FN = new Label()
                {
                    Name = "lbl" + mc.FirstName,
                    Content = mc.FirstName,
                };

            mgrid.Children.Add(FN);
            Grid.SetRow(FN, mgrid.RowDefinitions.Count - 2);
        }
    }
}

现在,在上面的代码中,我知道我应该Content = mc.FirstName以某种方式进行更改以使其绑定到类属性,但不知道如何,并且搜索并不能完全帮助我解决它。

任何人都知道我应该做什么?

标签: c#wpfclasspropertiesbinding

解决方案


您可以在后面的代码中添加一个绑定,如下所示:

 Label label = new Label() {
     Name = "lbl" + mc.FirstName
 };
 Binding binding = new Binding()
 {
      Mode = BindingMode.TwoWay,
      UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
      Path = new PropertyPath("FirstName")
 };
 label.SetBinding(ContentProperty, binding);

推荐阅读