当然有。您可以AppSettings
在两个窗口中创建属性DependencyProprerties
,然后在创建窗口时将属性绑定Settings
到Main
窗口的属性Settings
。也就是说,在 SettingsWindow 类中:
partial class SettingsWindow : Window {
public static readonly DependencyProperty AppSettingsProperty("AppSettings", typeof(AppSettings), typeof(SettingsWindow), new PropertyMetaData(null));
public AppSettings AppSettings {
get { return (AppSettings) GetValue(AppSettingsProperty); }
set { SetValue(AppSettingsProperty, value); }
}
}
然后,在Main
window类的代码后面:
partial class MainWindow : Window {
public static readonly DependencyProperty AppSettingsProperty("AppSettings", typeof(AppSettings), typeof(MainWindow), new PropertyMetaData(null));
public AppSettings AppSettings {
get { return (AppSettings) GetValue(AppSettingsProperty); }
set { SetValue(AppSettingsProperty, value); }
}
private void ShowSettingsWindowButton_Click(object sender, RoutedEventArgs e ) {
SettingsWindow settingsWindow = new SettingsWindow();
Binding appSettingsBinding = new Binding("AppSettings");
appSettingsBinding.Source = this;
appSettingsBinding.Path = new PropertyPath( "AppSettings" );
appSettingsBinding.Mode = BindingMode.TwoWay;
BindingOperations.SetBinding( this, AppSettingsProperty, appSettingsBinding );
settingsWindow.ShowDialog();
}
}
该Binding
机制将使两个对象中的属性保持同步。因此,如果在SettingsWindow
打开时将一个类中的属性值替换为不同的实例,SettingsWindows
则会通知更改并更新其副本。