代码之家  ›  专栏  ›  技术社区  ›  Jeff LaFay

WPF和ViewModel属性访问

  •  1
  • Jeff LaFay  · 技术社区  · 14 年前

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

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

    2 回复  |  直到 12 年前
        1
  •  3
  •   ChrisNel52    12 年前

    /// <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
  •  1
  •   ThomasAndersson    14 年前

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