- RegisterAttached 含义:使用指定的属性名称、属性类型和所有者类型注册附加属性
- 绑定方式:C#绑定、WPF绑定
- 例:需求DataViewModel为DataView的VM层,在DataViewModel中有ID属性,DataView需要根据ViewModel中的ID变化处理问题
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:
在DataView.cs文件中使用Binding属性,如下:
1 Binding binding = new Binding("ID"); 2 binding.Source = DataContext; 3 binding.Mode = BindingMode.OneWay; 4 this.SetBinding(MainWindow.IDProperty, binding);
绑定方式2:
在DataView.xaml文件中对控件的附加依赖属性进行绑定,如下:
<TextBlock Text="{Binding ID}" Width="100" Height="50" Background="DarkGray"/>