【问题标题】:WPF and ViewModel Property AccessWPF 和 ViewModel 属性访问
【发布时间】:2011-05-12 06:42:22
【问题描述】:

我的应用程序的主要组件是一个选项卡控件,其中包含 N 个视图,并且这些视图的数据上下文是一个单独的 ViewModel 对象。我在应用程序底部有一个状态栏,它包含一些文本框。我希望其中一个文本框反映当前选定选项卡的时间戳。时间戳是 ViewModel 对象的一个​​属性,它被设置为视图的数据上下文。

我是 WPF 新手,不确定如何将该属性绑定到状态栏。

【问题讨论】:

    标签: wpf data-binding mvvm viewmodel


    【解决方案1】:

    确保您的 ViewModel 实现 INotifyPropertyChanged。

    例如...

    /// <summary>
    /// Sample ViewModel.
    /// </summary>
    public class ViewModel : INotifyPropertyChanged
    {
        #region Public Properties
    
        /// <summary>
        /// Timestamp property
        /// </summary>
        public DateTime Timestamp
        {
            get
            {
                return this._Timestamp;
            }
            set
            {
                if (value != this._Timestamp)
                {
                    this._Timestamp = value;
    
                    // NOTE: This is where the ProperyChanged event will get raised
                    //       which will result in the UI automatically refreshing itself.
                    OnPropertyChanged("Timestamp");
                }
            }
        }
    
        #endregion
    
    
        #region INotifyPropertyChanged Members
    
        /// <summary>
        /// Event
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;
    
        /// <summary>
        /// Raise the PropertyChanged event.
        /// </summary>
        protected void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    
        #endregion
    
    
        #region Private Fields
    
        private DateTime _Timestamp;
    
        #endregion
    }
    

    【讨论】:

      【解决方案2】:

      类似:

      <TextBox Text="{Binding ElementName=tabControl, Path=SelectedItem.DataContext.Timestamp}" />
      

      取决于您的 tabcontrol 的 itemssource 是否是数据绑定的。

      【讨论】:

      • 使用 SelectedContent.DataContext.Timestamp 有点工作。除非我选择另一个选项卡然后再次选择该选项卡,否则它不会更新。当该属性发生变化时,我能做些什么来更新文本块?
      • 您所有的 ViewModel 是否都实现了 INotifyPropertyChanged?
      • @Chris,不,他们没有。我不知道那个界面,我是 WPF 的新手 :) 看起来我还有一些阅读要做。
      • 如果您的 ViewModel 实现了 INotifyPropertyChanged,那么只要您的 ViewModel 中的 Timestamp 属性发生更改,就会引发 PropertyChanged 事件。 WPF 将识别 PropertyChanged 事件并自动为您更新 UI。
      • @Chris,您能否使用示例实现的方法发布答案以引发我的 Timestamp 属性的事件?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-17
      • 2018-09-12
      • 1970-01-01
      • 2020-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多