双向绑定
2025/2/10原创小于 1 分钟约 200 字
1. xaml
<Window x:Class="WpfApp2.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:WpfApp2"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<Style TargetType="Grid">
<Setter Property="Background" Value="Aqua"></Setter>
</Style>
</Window.Resources>
<Grid Margin="100">
<TextBox Text="{Binding MyProperty ,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Height="30"></TextBox>
<TextBlock Text="{Binding MyProperty}" Width="100" Height="30"></TextBlock>
</Grid>
</Window>
2. cs后台
namespace WpfApp2
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public string text { get; set; }
private MyViewModel myView = new MyViewModel();
public MainWindow()
{
InitializeComponent();
text = "ab";
this.DataContext =myView;
}
}
}
3. ViewModel
namespace WpfApp2
{
public class MyViewModel:INotifyPropertyChanged
{
private string _myProperty;
public string MyProperty
{
get { return _myProperty; }
set
{
if (_myProperty != value)
{
_myProperty = value;
OnPropertyChanged(nameof(MyProperty));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}