在C#wpf中如何遍历网格并获取网格内的所有标签

所以你知道在c#中如何使用普通forms,你可以循环一个面板并获取其中的所有标签? 所以你可以这样做:

foreach(Label label in Panel.Controls) 

有没有办法为网格做这个? 就像是

 foreach(Lable lable in Grid) 

所以这个foreach可以在一个传递网格对象的函数中

 private void getLabels(Grid myGrid) { foreach(Label label in myGrid) } 

如果我这样做,它告诉我“错误CS1579:foreach语句不能对’System.Windows.Controls.Grid’类型的变量进行操作,因为’System.Windows.Controls.Grid’不包含’GetEnumerator’的公共定义”

有没有另一种方法可以做到这一点,我现在知道了吗?

任何帮助,将不胜感激。

通过Grid.Children迭代并将所有内容都转换为Label。 如果它不为null,则表示您已找到Label。

normal forms – WPF我们是2014年.Net Windows用户界面的正常方式。

如果你正在使用WPF,你需要抛弃从古代技术中获得的任何和所有概念,并理解并接受WPF心态

基本上,你不会在WPF中“迭代”任何东西,因为绝对没有必要这样做。

UI的职责是显示数据,而不是存储数据或操纵数据。 因此,您需要显示的任何数据都必须存储在正确的数据模型或ViewModel中 ,并且UI必须使用适当的DataBinding来访问该数据,而不是过程代码。

所以,例如,假设你有一个Person类:

 public class Person { public string LastName {get;set;} public string FirstName {get;set;} } 

您需要将UI的DataContext设置为以下列表:

 //Window constructor: public MainWindow() { //This is required. InitializeComponent(); //Create a list of person var list = new List(); //... Populate the list with data. //Here you set the DataContext. this.DataContext = list; } 

然后,您将要在ListBox或其他基于ItemsControl的UI中显示:

     

然后,您将需要使用WPF的数据模板function来定义如何在UI中显示Person类的每个实例:

            

最后,如果需要在运行时更改数据 ,并在UI中反映( 显示 )这些更改,则DataContext类必须实现INotifyPropertyChanged

 public class Person: INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string name) { var handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(name)); } private string _lastName; public string LastName { get { return _lastName; } set { _lastName = value; OnPropertyChanged("LastName"); } } private string _firstName; public string FirstName { get { return _firstName; } set { _firstName = value; OnPropertyChanged("FirstName"); } } } 

最后,迭代List并更改数据项的属性,而不是操纵UI:

 foreach (var person in list) person.LastName = "Something"; 

虽然离开了UI。