c# - 如何将类的属性列表绑定到一系列标签
问题描述
所以,搜索没有帮助,我对绑定世界有点陌生。
尽可能简化它:我有 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
以某种方式进行更改以使其绑定到类属性,但不知道如何,并且搜索并不能完全帮助我解决它。
任何人都知道我应该做什么?
解决方案
您可以在后面的代码中添加一个绑定,如下所示:
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);
推荐阅读
- visual-studio-code - VSCode 扩展访问语言提供者
- c++ - 如何以可读的方式读写“EVP_PKEY”中包含的公钥和私钥?
- java - JUnit 测试 FaceContext 和 Session 代码
- python - 如何在 Python 中动态重新加载函数?
- sql - 如何从 Teradata sql 中的大型查询结果集中选择一定数量的行
- python - 在python的numpy数组中查找元素的位置
- java - 检查两个列表中的元素
- javascript - Axios 上的 setInterval 获取和更新输出而不重复
- linux - 如何监控 SIMD 指令的使用量
- swagger - 无法将 go-swagger 参数连接到路由