0
点赞
收藏
分享

微信扫一扫

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

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

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

▲ 简单界面

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

绑定的效果:

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

▲ 绑定效果



举报

相关推荐

0 条评论