WPF 简单的单个 CLR 对象作为绑定的 Source 源 发表于 2021-04-10 | 分类于 编程爱好 | 评论数: | 阅读次数: WPF 中如何用最直接的手段将 CLR 对象作为绑定的 Source 源? ▲ 简单界面 XAML代码: 12345678910<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# 代码: 12345678910111213141516171819202122232425262728293031323334353637/// <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))); } }} 绑定的效果: ▲ 绑定效果 感谢支持! 打赏 微信支付 支付宝 本文作者: huvjie 本文链接: https://blog.huvjie.com/2021/04/10/210410N01/ 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!