1、binding源为非控件,而是C#类/实例
窗体(V)代码,
<Window x:Class="WpfBindingApp1.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:WpfBindingApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<TextBlock Width="160" Height="50" Text="年龄:" Margin="37,192,603,193" FontSize="20"/>
<TextBox Width="160" Height="50" x:Name="tb333" Text="{Binding Age}" Margin="134,173,506,212"/>
<TextBlock Width="160" Height="50" Text="姓名:" Margin="37,266,603,119" FontSize="20"/>
<TextBox Width="160" Height="50" x:Name="tb444" Margin="134,247,506,138" Text="{Binding person.Name}" />
<Button x:Name="btn111" Width="80" Height="60" Click="btn111_Click" Margin="360,299,360,76"/>
</Grid>
</Window>
C#后台(VM)代码,这里为了好看,可以把person类改名为xxViewModel
public class Person: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
if (PropertyChanged != null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name"));
}
}
}
}
public partial class MainWindow : Window, INotifyPropertyChanged //窗体底层cs代码
{
public event PropertyChangedEventHandler PropertyChanged;
public Person person { get; set; } = new Person(); // 1)要使用{ get; set; },令其作为属性,而不能是字段!
private int _age;
public int Age //这里也可以看作是(M)代码,直接把(binding源)属性写在同一个(即binding接收对象/UI所在的)窗体/页面类
{
get { return _age; }
set
{
_age = value;
if (PropertyChanged!= null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Age"));
}
}
}
public MainWindow()
{
InitializeComponent();
_age = 10;
person.Name = "Tom";
this.DataContext = this; //2)使用DataContext作为binding源 。注意窗体/页面类和binding接收控件是不一样,比如说binding接收控件绑定自身,并不是指它所在的窗体/页面类,而就是它这个控件自身。
}
private void btn111_Click(object sender, RoutedEventArgs e)
{
Age += 1;
person.Name += "+2" ;
}
}
标签:控件,PropertyChanged,xmlns,binding,例子,窗体,wpf,public From: https://www.cnblogs.com/castlewu/p/16931919.html