繁体   English   中英

如何将类的属性列表绑定到一系列标签

[英]How to bind a list of classes' property to a series of labels

因此,搜索没有帮助,我对绑定世界还是陌生的。

为了尽可能简化:我有2个窗口和一个类。 在第一个窗口中,我全局声明一个类List<MyClass> MyList = new List<MyClass>();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更改为将其绑定到class属性,但不知道如何进行,并且搜索并不能完全帮助我解决它。

有人知道我应该怎么做吗?

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

 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM