我的应用程序的主要组件是一个Tab控件,其中包含N个 View ,这些 View 的数据上下文是一个单独的ViewModel对象。我在应用程序的底部有一个状态栏,其中包含一些文本框。我希望其中一个文本框反射(reflect)当前所选选项卡的时间戳。时间戳是ViewModel对象的属性,该属性设置为 View 的数据上下文。

我是WPF newb,但不确定如何将该属性绑定(bind)到状态栏。

最佳答案

确保您的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
}

关于wpf - WPF和ViewModel属性访问,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4219242/

10-12 13:03
查看更多