WPF和ViewModel属性访问

时间:2010-11-18 20:27:35

标签: wpf data-binding mvvm viewmodel

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

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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

类似的东西:

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

根据tabcontrol的itemssource是否为数据绑定而略有不同。