gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 20:50:34 25 4
gpt4 key购买 nike

那么您知道在 C# 中如何使用普通形式循环遍历面板并获取其中的所有标签吗?所以你可以这样做:

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’不包含‘的公共(public)定义’获取枚举器'"

还有我现在知道的另一种方法吗?

如有任何帮助,我们将不胜感激。

最佳答案

normal forms - WPF 在 2014 年为我们提供了 正常 .Net Windows UI 的方式。

如果您正在使用 WPF,则需要抛开您从古老技术中获得的所有概念,并理解并接受 The WPF Mentality

基本上,您不会“迭代”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<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 功能来定义如何在 UI 中显示 Person 类的每个实例:

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

最后,如果您需要在运行时更改Data,并在 UI 中反射(reflect)(显示)这些更改,您的 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> 并更改数据项的属性,而不是操纵 UI:

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

同时保留 UI。

关于c# - 在 C# wpf 中如何遍历网格并获取网格内的所有标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22794445/

25 4 0