当前应用程序属性更改时如何引发事件

时间:2009-11-12 15:05:04

标签: wpf mvvm object

我有一个WPF应用程序。

在我的App.xaml.cs中,我保存登录用户的全名,如下所示:

App.Current.Properties [“FullName”] = GetValueFromDatabase();

我在同一个应用程序中有两个屏幕/窗口。

首先是用户scrren,它有一个可编辑的WPF数据网格,我可以更新当前用户的全名。   第二个是具有Label / TextBox控件的屏幕,该控件显示Application对象中的Current users fullname。

当两个窗口都打开时,如果我更改用户的全名并在第一个屏幕中保存更改。我想触发一个事件,以便它立即反映在第二个屏幕上?

我将这个事件挂钩到这个应用程序以及如何?

我正在使用MVVM模式和实体框架。

2 个答案:

答案 0 :(得分:0)

您应该使用dependency property或确保您的模型是INotifyPropertyChanged,以便其他人可以使用{Binding}

在屏幕或窗口中绑定它
// if your model is derived from a sub-class of DependencyObject....
class Model : DependencyObject 
{
    public static readonly DependencyProperty MyStringProperty = 
            DependencyProperty.Register("MyString", typeof(string), 
            typeof(IncidentGraphic), new UIPropertyMetadata(string.Empty));

    public string MyString
    {
        get { return (string)GetValue(MyStringProperty ); }
        set { SetValue(MyStringProperty , value); }
    }
}

/// recommended to use INotifyPropertyChanged
class Model : INotifyPropertyChanged
{
     private void NotifyChange(string property)
     {
         PropertyChangedEventHandler handler = this.PropertyChanged;
         if (handler != null)
         {
             handler(this, new PropertyChangedEventArgs(property));
         }
     }

     string m_MyString = string.Empty;
     public string MyString
     {
         get
         {
             return m_MyString ;
         }
         set
         {
             if ( value != this.m_MyString )
             {
                 this. m_MyString  = value;
                 NotifyChange("MyString");
             }
             }
     }
}

// in your xaml.....
    <TextBox Text="{Binding MyString}" />

答案 1 :(得分:0)

我已经实现了一个Mediator类,它充当了在两个Windows的ViewModel之间进行通信的媒介。

我参考了这篇文章:http://sachabarber.net/?p=477