如何在依赖属性上引发属性更改事件? [英] How To Raise Property Changed events on a Dependency Property?

查看:9
本文介绍了如何在依赖属性上引发属性更改事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有两个属性的控件.一个是 DependencyProperty,另一个是第一个的别名".当第一个事件发生变化时,如何为第二个事件(别名)引发 PropertyChanged 事件.

I have a control with two properties. One is a DependencyProperty, the other is an "alias" to the first one. How do I raise the PropertyChanged event for the second one (the alias) when the first one is changed.

注意:我使用的是 DependencyObjects,而不是 INotifyPropertyChanged(试过了,没用,因为我的控件是一个 ListVie 子类)

NOTE: I'm using DependencyObjects, not INotifyPropertyChanged (tried that, didn't work because my control is a ListVie sub-classed)

这样的东西.......

Something like this.....

protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
    base.OnPropertyChanged(e);
    if (e.Property == MyFirstProperty)
    {
        RaiseAnEvent( MySecondProperty ); /// what is the code that would go here?
    }    
}

如果我使用的是 INotify,我可以这样做...

If I were using an INotify I could do like this...

public string SecondProperty
{
    get
    {
        return this.m_IconPath;
    }
}

public string IconPath
{
    get
    {
        return this.m_IconPath;
    }
    set
    {
        if (this.m_IconPath != value)
        {
            this.m_IconPath = value;
        this.SendPropertyChanged("IconPath");
        this.SendPropertyChanged("SecondProperty");
        }
    }
}

在哪里可以从一个 setter 中针对多个属性引发 PropertyChanged 事件?我需要能够做同样的事情,只使用 DependencyProperties.

Where can I raise PropertyChanged events on multiple properties from one setter? I need to be able to do the same thing, only using DependencyProperties.

推荐答案

  1. 在您的类中实现 INotifyPropertyChanged.

在注册依赖属性时在属性元数据中指定回调.

Specify a callback in the property metadata when you register the dependency property.

在回调中,引发 PropertyChanged 事件.

In the callback, raise the PropertyChanged event.

添加回调:

public static DependencyProperty FirstProperty = DependencyProperty.Register(
  "First", 
  typeof(string), 
  typeof(MyType),
  new FrameworkPropertyMetadata(
     false, 
     new PropertyChangedCallback(OnFirstPropertyChanged)));

在回调中提高PropertyChanged:

private static void OnFirstPropertyChanged(
   DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
   PropertyChangedEventHandler h = PropertyChanged;
   if (h != null)
   {
      h(sender, new PropertyChangedEventArgs("Second"));
   }
}

这篇关于如何在依赖属性上引发属性更改事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆