【问题标题】:Problem with Dependency Property and PropertyChangedCallback in WPFWPF中的依赖属性和PropertyChangedCallback问题
【发布时间】:2019-04-17 11:18:15
【问题描述】:

在我的 CustomControl 中,我有 View 依赖属性。使用此控件的外部控件通过视图模型设置此属性。设置后,会触发 Refresh 方法并渲染视图!

到目前为止一切都很好!但是,如果我还希望它在 View 的属性发生更改时刷新。

也许我不是按照标准方式做的?我应该在控件上定义一个公共 Refresh() 方法并从外部调用它吗?如何使用指挥?

  public static readonly DependencyProperty ViewProperty =
     DependencyProperty.Register(
        "View", typeof(View),
        typeof(CustomControl), new PropertyMetadata(Refresh)
     );


  public View View
  {
     get => (View)GetValue(ViewProperty);
     set => SetValue(ViewProperty, value);
  }

  private static void Refresh(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
     // 
     MessageBox.Show("Refreshed!");
  }

   public sealed class View : INotifyPropertyChanged
   {
      private bool m_isDirty;

      public bool IsDirty
      {
         get => m_isDirty;
         set
         {
            m_isDirty = value;
            OnPropertyChanged();
         }
      }

      public event PropertyChangedEventHandler PropertyChanged;

      private void OnPropertyChanged([CallerMemberName] string propertyName = null)
      {
         PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
      }
   }

【问题讨论】:

    标签: c# wpf mvvm dependency-properties inotifypropertychanged


    【解决方案1】:

    您可以在回调中为ViewPropertyChanged 事件连接一个事件处理程序:

    private static void Refresh(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        MessageBox.Show("Refreshed!");
    
        View newView = e.NewValue as View;
        if (newView != null)
            newView.PropertyChanged += NewView_PropertyChanged;
    
        View oldView = e.OldValue as View;
        if (oldView != null)
            oldView.PropertyChanged -= NewView_PropertyChanged;
    }
    
    private static void NewView_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        View view = (View)sender;
        //view updated...
    }
    

    【讨论】:

    • 听起来是一个合理的解决方案。谢谢你。但是它会在 View 中的每个属性更改时触发!而且我不想在这里硬编码属性名称!是不是可以在 Control 和 mechansim 中有一些 Refresh() 方法,以便我可以通过外部绑定强制它执行?
    • 只要视图触发 PropertyChanged 事件就会触发。您指的是什么属性名称?
    • 我的视图可能具有引发 OnPropertyChanged 的​​其他属性,例如名称等。我只想更改视图的特定属性以触发 CustomControl 上的 Refresh()。我想要的是 CustomControl 中的一种机制,以便我可以在 Control 之外绑定到我的 ViewModel。
    • 也许我应该在 CustomControl 中有一个布尔 RefreshRequested DP 并将其绑定到控件外的 imy 视图模型?
    • 要么检查在控件中引发事件的属性的名称,要么在视图中引发另一个事件。
    猜你喜欢
    • 2013-05-25
    • 2013-01-31
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-27
    • 2010-11-11
    相关资源
    最近更新 更多