tôi cho rằng năm bằng cách sử dụng sự kiện DataContextChanged tĩnh tin để biết khi nào yr DataContext thay đổi ngay
đây là một số mã của tôi Đây là những gì tôi làm
public static readonly DependencyProperty ApplicationDataContextProperty =
DependencyProperty.Register("ApplicationDataContext",
typeof(Object),
typeof(MyControl),
new PropertyMetadata(MyControl_DataContextChanged));
// my constructor
public MyControl()
{
InitializeComponent();
if (!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
{
SetBinding(ApplicationDataContextProperty, new Binding());
}
}
// my event
private static void MyControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
MyControl thisControl = sender as MyControl
if (thisControl != null)
{
INotifyPropertyChanged propertyChanged;
propertyChanged = e.OldValue as INotifyPropertyChanged;
if (propertyChanged != null)
propertyChanged.PropertyChanged -= thisControl.propertyChanged_PropertyChanged;
propertyChanged = e.NewValue as INotifyPropertyChanged;
if (propertyChanged != null)
propertyChanged.PropertyChanged += thisControl.propertyChanged_PropertyChanged;
}
}
// my 2e event
void propertyChanged_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "ListWithUsers")
LoadGrid();
}
Tại sao bạn làm cái đó? – MBen
Một chút phức tạp để giải thích, nhưng về cơ bản là đối tượng là ngữ cảnh dữ liệu (một lớp trợ giúp để trực quan hóa dữ liệu của lớp khác) biết rằng điều khiển này trình bày một giao diện để chỉnh sửa đối tượng được lưu trữ trong thuộc tính được chỉ định trong đường dẫn biểu thức ràng buộc. – JoshG