wpf 为PropertyChanged事件mvvm订阅只读属性

ubby3x7f  于 2023-08-07  发布在  其他
关注(0)|答案(2)|浏览(117)

在视图模型中,有一个属性依赖于另一个属性值:

private int _property;
        public int Property
        {
            get
            {
                return _property;
            }
            set
            {
                SetProperty(ref _property, value, () => Property);
            }
        }
        public int DependentProperty => Property + SomeLogic;

字符串
和视图:

<TextBlock Text="{Binding DependentProperty}" />


我想在_属性更改时更新视图
我发现:this question说你必须订阅Property的PropertyChanged事件,但我不知道如何订阅。

waxmsbnn

waxmsbnn1#

DependentProperty被称为计算属性。在本例中,INotifyPropertyChanged.PropertyChanged事件通过调用SetProperty方法隐式引发。您所要做的就是显式引发计算属性的事件。
通常,您已经有了一个事件调用器方法实现,SetProperty方法也在内部使用它。
例如,如果使用.NET社区工具包,则已经继承了可以调用的protected virtual ObservableObject.OnPropertyChanged(propertyName: string):void方法。

private int _property;
public int Property
{
  get => _property;
  set
  {
    // Implicitly raises the PropertyChanged event for this property
    // because SetProperty is calling OnPropertyChanged (event invocator method) internally.
    SetProperty(ref _property, value, () => Property);

    // Raise the PropertyChanged event explicitly for the computed property
    OnPropertyChanged(nameof(DependentProperty));
  }
}

public int DependentProperty => Property + SomeLogic;

字符串
当然,如果你想避免从计算属性所依赖的每个属性中显式引发PropertyChanged事件,你可以观察所需的属性:

private int _property;
public int Property
{
  get => _property;
  set => SetProperty(ref _property, value, () => Property);
}

public int DependentProperty => Property + SomeLogic;

public ViewModel()
{
  TrackDependentPropertySourceProperties();
}

private void TrackDependentPropertySourceProperties()
{
  this.PropertyChanged += OnDependentPropertySourcePropertiesChanged;
}

// Assume that DependentProperty depends on three other properties
// (use three to highlight the pattern)
private void OnDependentPropertySourcePropertiesChanged(object sender, PropertyChangedEventArgs e)
{
  switch (e.PropertyName)
  {
    case nameof(Property):
    case nameof(SomeOtherProperty):
    case nameof(AThirdProperty):
      OnPropertyChanged(nameof(DependentProperty));
  }
}

vm0i2vca

vm0i2vca2#

你需要实现INotifyPropertyChanged接口到模型。
然后实施

protected void OnPropertyChanged(string name)
{
     PropertyChangedEventHandler handler = PropertyChanged;
     if (handler != null)
     {
         handler(this, new PropertyChangedEventArgs(name));
     }
}

字符串
当你set的时候,属性就调用OnPropertyChanged(<ProperyName>)

建议:不要将业务逻辑放入模型本身。

相关问题