在 WPF 中的两个窗口之间共享同一对象
本文关键字:之间 窗口 共享 对象 两个 WPF | 更新日期: 2023-09-27 18:33:08
我有代表我的AppSettings
的类我有Main
窗口和Settings
窗口。
每个窗口都包含对象AppSettings
的实例
所以这两个对象是不同的。如果Settings
窗口中的对象AppSettings
发生更改,则更改不会反映在Main
窗口的AppSettings
中。
有什么方法可以在窗口之间共享AppSettings
对象,所以我只有一个实例?
我尝试创建共享基类,但出现错误
Partial declarations of "class name" must not specify different base classes
可以在一个类中创建静态属性,并在另一个类中创建该静态属性的包装器属性。
此外,如果要将此属性绑定到UI,则不需要两个属性。
这个答案与主题有关,但我找到了其他更简单的方法来完成要求的事情,以便将来可以帮助任何人。在每个 WPF 应用程序中,都创建了 app.xaml 和 app.xaml.cs。因此,在app.xaml中创建一个设置对象.cs它看起来像这样:
namespace WpfApplication
{
public partial class App : Application
{
// Settings :
public int setting_1 { get; set; } //some setting variable
public string setting_2 { get; set; } //some other setting variable
}
}
现在要从不同的窗口引用这个对象,你可以使用: ((App)Application.Current).setting_1
有什么方法可以在窗口之间共享应用程序设置对象,以便我只有一个实例?
您需要某种方式才能使两个窗口获得相同的引用。 如果将对同一AppSettings
对象的引用传递给两个窗口,这应该可以正常工作。
当然有。 可以使两个窗口中的 AppSettings
属性DependencyProprerties
,然后在创建Settings
窗口时将Settings
中的属性绑定到Main
窗口的属性。 也就是说,在 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
窗口类的代码隐藏中:
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
将收到更改通知并更新其副本。
你可以在你的项目中有一个像"Utils"这样的类,其属性如下:
Public Shared(or Static in C#) AppSettings As YourObjectType
然后在窗口的 xaml 中以 Utils.AppSetings 的模式双向