是否存在依赖属性更改时的通知机制?

Mar*_*ram 2 .net silverlight dependency-properties silverlight-2.0

在Silverlight应用程序中,我试图找出usercontrol上的属性何时发生了变化.我对一个特定的DependencyProperty很感兴趣,但不幸的是控件本身并没有实现INotifyPropertyChanged.

有没有其他方法可以确定价值是否已经改变?

ama*_*int 5

您可以.至少我做到了.仍然需要看到利弊.

 /// Listen for change of the dependency property
    public void RegisterForNotification(string propertyName, FrameworkElement element, PropertyChangedCallback callback)
    {

        //Bind to a depedency property
        Binding b = new Binding(propertyName) { Source = element };
        var prop = System.Windows.DependencyProperty.RegisterAttached(
            "ListenAttached"+propertyName,
            typeof(object),
            typeof(UserControl),
            new System.Windows.PropertyMetadata(callback));

        element.SetBinding(prop, b);
    }
Run Code Online (Sandbox Code Playgroud)

现在,您可以调用RegisterForNotification来注册元素属性的更改通知,例如.

RegisterForNotification("Text", this.txtMain,(d,e)=>MessageBox.Show("Text changed"));
            RegisterForNotification("Value", this.sliderMain, (d, e) => MessageBox.Show("Value changed"));
Run Code Online (Sandbox Code Playgroud)

http://amazedsaint.blogspot.com/2009/12/silverlight-listening-to-dependency.html上查看我的帖子.