public class DataViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public void OnPorpertyChanged(string name) { if (PropertyChanged != null) { PropertyChanged.Invoke(this, new PropertyChangedEventArgs(name)); } } public int ID { get { return id; } set { id = value; OnPorpertyChanged("ID"); } } private int id; }
/// <summary> /// DataView.xaml 的交互逻辑 /// </summary> public partial class DataView : UserControl { public DataView() { InitializeComponent(); this.DataContext = new DataViewModel(); } public int ID { get { return (int)GetValue(IDProperty); } set { SetValue(IDProperty, value); } } public static readonly DependencyProperty IDProperty = DependencyProperty.RegisterAttached("ID", typeof(int), typeof(DataView), new PropertyMetadata(OnIDChanged)); private static void OnIDChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var control = d as MainWindow; if (control != null) { control.Background = Convert.ToInt32(e.NewValue) > 0 ? Brushes.Red : Brushes.Green; } } }
绑定方式1:this
在DataView.cs文件中使用Binding属性,以下:spa
1 Binding binding = new Binding("ID"); 2 binding.Source = DataContext; 3 binding.Mode = BindingMode.OneWay; 4 this.SetBinding(MainWindow.IDProperty, binding);
绑定方式2:code
在DataView.xaml文件中对控件的附加依赖属性进行绑定,以下:blog
<TextBlock Text="{Binding ID}" Width="100" Height="50" Background="DarkGray"/>