【问题标题】:Refreshing a wpf databinding after object has been updated更新对象后刷新 wpf 数据绑定
【发布时间】:2009-01-18 16:10:14
【问题描述】:

我有一个连接到视图的演示器中的对象。在我的 XAMTL 中,我有以下内容:

<Label Content="{Binding ElementName=PSV, Path=Presenter.Portfolio.Name}"/>

现在当控件创建时,Portfolio 为空,然后我运行另一个设置 Portfolio 的方法。我已经实现了 INotifyPropertyChanged,但到目前为止,我还无法触发连接到绑定。

有人可以给我提示吗?我可以绑定到属性的属性吗?

【问题讨论】:

    标签: c# wpf data-binding xaml


    【解决方案1】:

    绑定始终适用于您需要将 Presenter 设置为本地 DataContext 的 DataContext。例如,您可以在 Window 或 UserControl 的构造函数中执行此操作:

    this.DataContext = new Presenter();
    

    然后您的绑定将更改为:

    <Label Content="{Binding ElementName=PSV, Path=Portfolio.Name}"/>
    

    之前路径的 Presenter 部分隐含在 DataContext 中。

    这样,DataContext 正在监视 NotifyChanged 事件,并在 Portfolio 从 null 变为具有值时正确更新视图。

    在回答您问题的最后一部分时,绑定到属性的属性确实有效。

    【讨论】:

      【解决方案2】:
      【解决方案3】:

      由于您已实现 INotifyPropertyChanged,您是否确保在 Portfolio.Name 设置器中触发 PropertyChanged 事件?

      string _name;
      public string Name
      {
      get 
      {
         return _name;
      }
      set
      {
         _name = value;
         // Alert the databinding engine about changes to the source value
         OnPropertyChanged("Name");
      }
      
      void OnPropertyChanged(string propertyName)
      {
         if (PropertyChanged != null)
            PropertyChanged(propertyName);
      }
      
      #region INotifyPropertyChanged members
      public event PropertyChangedEventHandler PropertyChanged;
      #endregion
      

      【讨论】:

        【解决方案4】:

        如果你正确地实现了INotifyPropertyChanged,这将工作得很好。可以尝试的一些事情:

        1. 尝试在演示者的构造函数中设置一个带有虚拟名称的虚拟投资组合,以便确保绑定实际上是正确的。
        2. 如果在 #1 之后仍然无法正常工作,请在输出窗口中查看任何绑定错误。
        3. 如果它在 #1 之后确实有效,请确保您设置的投资组合在构建时具有名称。如果没有,您的投资组合类还需要实现 INotifyPropertyChanged 并在设置 Name 时引发事件。

        如果失败,请发布您的代码。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-06-11
          • 2011-08-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多