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

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

▲ 简单界面

XAML代码:

<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# 代码:

/// <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))); }
    }
}

绑定的效果:

▲ 绑定效果
posted @ 2021-09-29 08:32  double64  阅读(115)  评论(0)    收藏  举报