FrameworkElement具有DataContext属性,代表绑定的数据源,在开发的时候有时需要监听其变化,在WinRt框架上有DataContext属性,但是在Sliverlight框架下没有,在此自己实现了该接口的子类。代码如下:
namespace xxx
{
public delegate void DataContextChangedHandler(object sender, object newData);
public class NotifyUserControl : FrameworkElement
{
public NotifyUserControl(){
SetBinding(MyDataContextChangedProperty,new Binding());
}
public event DataContextChangedHandler DataContextChanged;
private static readonly DependencyProperty MyDataContextChangedProperty =
DependencyProperty.Register("MyDataContext", typeof(object), typeof(NotifyUserControl), new PropertyMetadata(null, (DependencyObject d, DependencyPropertyChangedEventArgs e) =>
{
var view = d as NotifyUserControl;
if (view.DataContextChanged != null)
{
view.DataContextChanged(view, e.NewValue);
}
}));
}
}