【问题标题】:Is it possible to use attributes to automatically raise an event on a property change是否可以使用属性在属性更改时自动引发事件
【发布时间】:2009-06-11 11:11:51
【问题描述】:

我发现自己经常写这段代码:

    private int _operationalPlan;
    public int OperationalPlan
    {
        get
        {
            return _operationalPlan;
        }
        set
        {
            _operationalPlan = value;
            RaisePropertyChanged();
        }
    }

    private void RaisePropertyChanged()
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new
                                      PropertyChangedEventArgs("PlansSelected"));
        }
    }

我想知道是否可以编写一个可以添加到属性中以自动引发事件的属性。 IE。像这样:

[RaiseOnSet("ProperyChanged", "PropertyChangedEventArgs", "PlansSelected")]
public int OperationalPlan
{
    get
    {
        return _operationalPlan;
    }
    set
    {
        _operationalPlan = value;
        RaisePropertyChanged();
    }
}

在我去尝试实现这个之前,我想知道:

  • 此功能是否在 .net 框架中
  • 有人试过这个设施吗
  • 如果可能的话
  • 如果有任何我应该避免的死胡同

【问题讨论】:

    标签: c# .net data-binding events attributes


    【解决方案1】:

    为此,您需要一个适用于 .NET 的 AOP 框架,例如 PostSharpAOP.NET

    【讨论】:

      【解决方案2】:

      如果你准备使用一个帮助类来包装你可以这样做的属性值。但这意味着任何访问该属性的客户端都需要解包该值。

      另一种方法是使用辅助类型,请参阅 WPF 和 WF 使用(不同的)DependencyProperty。但是您不会获得自动实现的属性。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-28
        • 1970-01-01
        • 2011-01-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多