xaml
<Window x:Class="测试binding.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:测试binding"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<Button Content="{Binding Path=aa}" ></Button> //banding aa 当cd类的name值改变时在view层显示
<DockPanel Height="100">
<Button Content="liushaui" Click="btn"></Button> //写了个click事件来改变数据
</DockPanel>
</StackPanel>
</Window>
MainWindow.xaml.cs
using System;
using System.Windows;
namespace 测试binding
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
private cd cd = new cd(); //将cd binding类 实例化
public MainWindow()
{
InitializeComponent();
this.DataContext = this.cd; //设置数据源为cd 类的
}
private void btn(object sender, RoutedEventArgs e)
{
Random r = new Random();
int i= r.Next();
cd.name = i.ToString(); //改变cd类的 name 的值
}
}
public class cd: DependencyObject
{
public static DependencyProperty nameProperty;
public string name
{
#region
get
{
return (string)GetValue(nameProperty);
}
set
{
SetValue(nameProperty , value);
}
#endregion
}
public event DependencyPropertyChangedEventHandler OnDependencyPropertyChanged;
protected static void PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
#region
cd mn = (cd)d;
if (mn.OnDependencyPropertyChanged != null)
{
mn.OnDependencyPropertyChanged(d, e);
}
#endregion
}
static cd()
{
FrameworkPropertyMetadata metadata = new FrameworkPropertyMetadata(""); //默认值为空
metadata.PropertyChangedCallback = new PropertyChangedCallback(PropertyChanged);
cd.nameProperty = DependencyProperty.Register("aa", typeof(string), typeof(cd), metadata); //生成 aa binding
}
public cd()
{
#region
this.name ="aaaaaa"; // 这个是初始值
#endregion
}
}
}
本文介绍了一个使用 WPF 的 Binding 特性进行数据绑定的例子。通过实例代码展示了如何将 UI 控件与 ViewModel 中的数据进行绑定,并实现了数据的双向更新。具体包括 XAML 文件中 Button 的 Content 属性绑定到 ViewModel 中的 cd 类属性,以及点击事件触发数据更改的过程。

被折叠的 条评论
为什么被折叠?



