DataBinding 是 WPF 在 UI 中显示和收集数据的最常用方式
试试这个:
<Window x:Class="WpfApp3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp3"
mc:Ignorable="d"
Title="MainWindow"
Height="350"
Width="525">
<Grid>
<TextBox Text="{Binding Path=SomeText, UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Left"
Margin="101,83,0,0"
VerticalAlignment="Top"
Width="75" />
<TextBlock Text="{Binding SomeText}"
HorizontalAlignment="Left"
Margin="101,140,0,0"
VerticalAlignment="Top"
Width="75" />
</Grid>
</Window>
窗口代码:
public partial class MainWindow : Window
{
private readonly AViewModel viewModel = new AViewModel();
public MainWindow()
{
InitializeComponent();
this.DataContext = viewModel;
}
}
以及包含您要显示和收集的数据的 ViewModel 的代码:
public class AViewModel : INotifyPropertyChanged
{
private string someText;
public string SomeText
{
get
{
return someText;
}
set
{
if (Equals(this.someText, value))
{
return;
}
this.someText = value;
this.OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(
[CallerMemberName]string propertyName = null)
{
this.PropertyChanged?.Invoke(
this,
new PropertyChangedEventArgs(propertyName));
}
}
虽然这对于一个简单的场景来说看起来很复杂,但它有很多优点:
- 您可以在不创建 UI 的情况下为 ViewModel 编写自动化(单元)测试
- 添加额外的字段和逻辑很简单
- 如果 UI 需要更改,ViewModel 并不总是需要更改
该机制的核心是 Xaml 中的 {Binding ...} 位,它告诉 WPF 在 TextBox 的 Text 属性和分配给 DataContext 的对象的 SomeText 属性之间同步数据。
其他重要位是:
- 在窗口的构造函数中设置 DataContext 和
- 在 ViewModel 中,当 SomeText 属性更改时引发 PropertyChanged 事件,以便通知绑定。
请注意,这只是 DataBinding 的一个基本示例,可以在此代码中进行许多改进。