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