我有两个窗口。在第一个窗口中,我想用一些偏好值(例如"MaxWords"(开始第二个窗口。第二个窗口包含一个具有INotifyPropertyChanged接口的类。这正如预期的那样。。。
public partial class PreviewPreferences : Window
{
public PreviewPreferences()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
}
public class ViewModel
{
public Preferences preferences { get; private set; }
public ViewModel()
{
preferences = new Preferences();
}
}
public class Preferences : INotifyPropertyChanged
{
private int _maxWords = 10;
/// <summary>
/// Default constructor
/// </summary>
public Preferences() { }
/// <summary>
/// Max words
/// </summary>
public int MaxWords
{
get { return this._maxWords; }
set { this._maxWords = value; this.OnPropertyChanged("MaxWords"); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
第二个窗口应该更新第一个窗口,并将一些用户控件添加到网格中。问题不在于如何添加控件。。。更重要的是如何从值MaxWords更改的首选类中引发事件?
private void button_preview_preferences_Click(object sender, RoutedEventArgs e)
{
PreviewPreferences previewPreferences = new PreviewPreferences();
previewPreferences.Show();
Preferences preferences = new Preferences();
preferences.PropertyChanged += HandleChangedPreferences;
}
private void HandleChangedPreferences(object sender, PropertyChangedEventArgs e)
{
// this will never be raised
for (int i = 0; i < MaxWords; i++)
{
...
}
}
在button_preview_Preferences_Click方法中有两个Preferences实例。第一个也是重要的一个(更改的(隐藏在PreviewPreferences DataContext:中
private void button_preview_preferences_Click(object sender, RoutedEventArgs e)
{
var previewPreferences = new PreviewPreferences();
var preferences = (previewPreferences.DataContext as ViewModel).preferences;
preferences.PropertyChanged += HandleChangedPreferences;
previewPreferences.Show();
}
我建议颠倒逻辑-在ViewModel之外创建首选项,并在PreviewPreferences视图之外创建ViewModel:
public partial class PreviewPreferences : Window
{
public PreviewPreferences()
{
InitializeComponent();
}
}
public class ViewModel
{
public Preferences preferences { get; private set; }
public ViewModel(Preferences p)
{
preferences = p;
}
}
private void button_preview_preferences_Click(object sender, RoutedEventArgs e)
{
var preferences = new Preferences();
preferences.PropertyChanged += HandleChangedPreferences;
var previewPreferences = new PreviewPreferences();
previewPreferences.DataContext = new ViewModel(preferences);
previewPreferences.Show();
}