双向绑定 TwoWay MVVM

时间:2023-03-08 19:09:21
双向绑定  TwoWay  MVVM

1前台代码

  <Grid>
<StackPanel >
<Grid x:Name="gridOne">
<Grid.Resources>
<Style TargetType="TextBlock">
<Setter Property="FontSize" Value="34"/>
</Style>
</Grid.Resources>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<TextBlock Text="姓名:" />
<TextBlock Grid.Column="1" Text="{Binding Name}"/>
<TextBlock Grid.Row="1" Text="城市:" />
<TextBlock Grid.Column="1" Grid.Row="1" Text="{Binding City}"/>
</Grid>
<Grid x:Name="gridTwp">
<Grid.Resources>
<Style TargetType="TextBlock">
<Setter Property="FontSize" Value="34"/>
</Style>
</Grid.Resources>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<TextBlock Text="姓名1:" />
<TextBox Name="txtName" Grid.Column="1" Text="{Binding Name,Mode=TwoWay}"/>
<TextBlock Grid.Row="1" Text="城市1:" />
<TextBox Name="txtCity" InputScope="ChineseFullWidth" Grid.Column="1" Grid.Row="1" Text="{Binding City,Mode=TwoWay}"/>
</Grid>
</StackPanel>
</Grid>

2后台方法

  public class Person : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string property="")
{
if (PropertyChanged!=null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
private string _name; public string Name
{
get
{
return _name;
} set
{
if (_name!=value)
{
_name = value;
OnPropertyChanged();
}
}
}
private string _city; public string City
{
get
{
return _city;
} set
{
if (_city != value)
{
_city = value;
OnPropertyChanged();
}
}
} }

3数据绑定

    Person ps = new Person { Name="小刘" ,City="北京" };
gridOne.DataContext = ps;
gridTwp.DataContext = ps;