【问题标题】:Property depending on property from another class属性取决于另一类的属性
【发布时间】:2014-01-06 00:04:28
【问题描述】:

我有一个使用 Fody 将 INotifyPropertyChanged 注入属性的 Windows Phone 8 应用程序。 我有 Class First,属性 A 绑定到 View 中的文本框:

[ImplementPropertyChanged]
public class First
{
    public int A { get; set; }

    public int AA { get {return A + 1; } }
}

第二类属性 B 取决于属性 A(也绑定到文本框):

[ImplementPropertyChanged]
public class Second
{
    private First first;

    public int B { get {return first.A + 1; } }
}

更新 A 和 AA 工作正常,但是 B 不会在 first.A 更改时自动更新。有没有一种简单干净的方法来使用 fody 实现这种自动更新,还是我必须创建自己的事件来处理它?

【问题讨论】:

    标签: c# mvvm windows-phone-8 inotifypropertychanged fody-propertychanged


    【解决方案1】:

    我对 Fody 不熟悉,但我怀疑这是因为 Second.B 上没有二传手。 Second 应该订阅 First 中的更改,如果 First.A 是被更改的属性,那么应该使用 B 的(私有)setter。

    或者订阅 First 然后调用 B 属性更改事件:

    [ImplementPropertyChanged]
    public class Second
    {
        private First first;
    
        public int B { get {return first.A + 1; } }
    
        public Second(First first)
        {
            this.first = first;
            this.first.OnPropertyChanged += (s,e) =>
            {
                if (e.PropertyName == "A") this.OnPropertyChanged("B");
            }
    }
    

    【讨论】:

    • Setter 不需要更新视图。我在 First 中添加了属性 AA,当 A 更改时它会更新得很好。我要的是 Fody 功能,以避免在 Second 中创建手动订阅。
    • 其实看Fody是必须的。在拥有类内部的情况下,它只是自动注入到代码中:github.com/Fody/PropertyChanged
    • 我之前看到过,但是,这并不能解决我的问题。当然,我可以添加一个事件并在 Second 中处理它,方法是使用私有设置器设置 B 以强制更新,但不幸的是,该解决方案不可扩展。
    • 看起来 Fody 不是你的灵丹妙药,因为它只会将代码注入到拥有的类中。你看过 ReactiveUI 吗?它可能会提供更优雅的东西(但仍然有点手动)。
    • 根据您的编辑:不能在具有 [ImplementPropertyChanged] 属性的类中使用 OnPropertyChanged 事件。也许 Fody 确实没有为我的问题提供解决方案,但是似乎仍然可以有一种类似于您提供的简单方法。
    【解决方案2】:

    我最终按照 SKall 建议的方式使用标准 INotifyPropertyChanged。

    public class First : INotifyPropertyChanged
    {
        public int A { get; set; }
    
        public int AA { get {return A + 1; } }
    
        (...) // INotifyPropertyChanged implementation
    }
    
    public class Second : INotifyPropertyChanged
    {
        private First first;
    
        public Second(First first)
        {
            this.first = first;
            this.first.PropertyChanged += (s,e) => { FirstPropertyChanged(e.PropertyName);
    
            public int B { get {return first.A + 1; } }
    
            protected virtual void FirstPropertyChanged(string propertyName)
            {
                if (propertyName == "A")
                    NotifyPropertyChanged("B");
            }
    
            (...) // INotifyPropertyChanged implementation
        }
    };
    

    【讨论】:

      猜你喜欢
      • 2012-07-15
      • 2015-08-09
      • 2018-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-03
      • 2017-03-10
      • 1970-01-01
      相关资源
      最近更新 更多