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>
最后,如果您需要在运行时更改数据,并将这些更改反映(显示)在 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> 并更改数据项的属性,而不是操纵 UI:
foreach (var person in list)
person.LastName = "Something";
同时保留 UI。