【问题标题】:How to bind a list of classes' property to a series of labels如何将类的属性列表绑定到一系列标签
【发布时间】:2019-07-14 00:52:27
【问题描述】:

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

尽可能简化它: 我有 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 以使其绑定到类属性,但不知道如何,并且搜索并不能完全帮助我解决它。

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

【问题讨论】:

  • 在网上搜索 MVVM 并阅读一些关于此模式的文章。然后创建一个具有ObservableCollection<MyClass> MyList 属性的视图模型类。将两个 Windows 的 DataContext 分配给同一个视图模型实例。在应该显示列表的窗口中,使用 ItemsControl(或 ListBox、ListView 或 DataGrid)并将其 ItemsSource 属性绑定到 MyList。将 ICommand 添加到视图模型,从而将元素添加到 MyList。将另一个窗口中的按钮绑定到该命令。
  • 在做这一切之前,请仔细阅读Data Binding OverviewData Templating Overview。你现在拥有的是一个完全错误的方法。在 WPF 中,您通常不应该在后面的代码中创建 UI 元素。扔掉你的代码,用 MVVM 重新开始。

标签: c# wpf class properties binding


【解决方案1】:

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

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

【讨论】:

  • Mode=TwoWay(因此还有UpdateSourceTrigger=PropertyChanged)在标签的 Content 属性的绑定中完全没有意义。控件从不主动更新自己的内容。除此之外,Binding 缺少源对象(即 DataContext、Source、RelativeSource 或 ElementName)。
  • 正确,我的错。我刚刚从我的项目中选择了这个,我将这个片段用于 TextBox 并且没有想到它是一个标签。
猜你喜欢
  • 1970-01-01
  • 2011-01-20
  • 2021-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-08
  • 2012-07-11
  • 2018-02-28
相关资源
最近更新 更多