在C#中wpf如何通过网格循环并获取网格中的所有标签
所以,你知道如何在C#中使用普通窗体,你可以通过面板循环并获得其中的所有标签? 所以,你可以做这样的事情:在C#中wpf如何通过网格循环并获取网格中的所有标签
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并将所有东西都转换为标签。如果它不为空,则找到一个标签。
normal forms
- WPF我们在2014年
做的.Net的Windows用户界面如果你使用WPF工作的正常方式,则需要后面的任何和所有的概念来让你从古老的技术了,了解并拥抱The WPF Mentality。
基本上,你不会“遍历”WPF中的任何东西,因为绝对不需要这样做。
的UI的责任是显示数据,而不是店它也不操纵它。因此,无论您需要显示的数据必须存储在适当的数据模型或ViewModel中,用户界面必须使用适当的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<Person>();
//... Populate the list with data.
//Here you set the DataContext.
this.DataContext = list;
}
那么你将要展示在ListBox
或另一ItemsControl
基于UI:
<Window ...>
<ListBox ItemsSource="{Binding}">
</ListBox>
</Window>
然后你需要使用WPF的Data Templating能力来定义如何显示Person
类的每个实例在UI:
<Window ...>
<Window.Resources>
<DataTemplate x:Key="PersonTemplate">
<StackPanel>
<TextBlock Text="{Binding FirstName}"/>
<TextBlock Text="{Binding LastName"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<ListBox ItemsSource="{Binding}"
ItemTemplate="{StaticResource PersonTemplate}"/>
</Window>
最后,如果你需要在运行时改变数据,和有这些变化反映(显示)的UI,你的DataContext类必须Implement 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<Person>
并更改数据项公关operties而不是操纵UI:
foreach (var person in list)
person.LastName = "Something";
,同时保留UI。