WPF 简单的单个 CLR 对象作为绑定的 Source 源

WPF 中如何用最直接的手段将 CLR 对象作为绑定的 Source 源?

▲ 简单界面

XAML代码:

1
2
3
4
5
6
7
8
9
10
<Window
<!--省略一些必要的命名空间-->

<StackPanel Orientation="Vertical">
<TextBlock Text="姓名:" Width="150" FontSize="15" Margin="0 10 0 0"/>
<TextBox x:Name="txbName" Height="50" Width="150" BorderBrush="Black" BorderThickness="1" VerticalContentAlignment="Center" FontSize="20" FontWeight="Bold"/>
<TextBlock Text="年龄:" Width="150" FontSize="15" Margin="0 10 0 0"/>
<TextBox x:Name="txbAge" Height="50" Width="150" BorderBrush="Black" BorderThickness="1" VerticalContentAlignment="Center" FontSize="20" FontWeight="Bold"/>
</StackPanel>
</Window>

C# 代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

stu = new Student();
Binding binding = new Binding() { Source = stu, Path = new PropertyPath(nameof(stu.Name)) };
txbName.SetBinding(TextBox.TextProperty, binding);
Binding binding1 = new Binding(nameof(stu.Age)) { Source = stu };
BindingOperations.SetBinding(txbAge, TextBox.TextProperty, binding1);
}

private Student stu = null;
}

public class Student:INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

private string _name = "小明";
public string Name
{
get { return _name; }
set { _name = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Name))); }
}

private int _age = 10;
public int Age
{
get { return _age; }
set { _age = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Age))); }
}
}

绑定的效果:

▲ 绑定效果
感谢支持!