在 WPF 中的两个窗口之间共享同一个对象 [英] Share the same object between two windows in WPF
问题描述
我有代表我的 AppSettings
的类我有 Main
窗口和 Settings
窗口.
每个窗口都包含对象AppSettings
所以这是两个不同的对象.如果Settings
窗口中的对象AppSettings
发生更改,则更改不会反映在Main
窗口的AppSettings
中.>
有什么办法可以在窗口之间共享 AppSettings
对象,所以我只有一个实例?
我尝试创建共享基类但出现错误
类名"的部分声明不能指定不同的基类
我知道这个答案与主题不符,但我找到了其他更简单的方法来做被问到的事情,以便将来可以帮助任何人.在每个 WPF 应用程序中,都会创建 app.xaml 和 app.xaml.cs.所以在 app.xaml.cs 中创建一个设置对象,它看起来像这样:
命名空间 WpfApplication{公共部分类 App : 应用程序{//设置:公共 int setting_1 { 获取;放;}//一些设置变量公共字符串 setting_2 { 获取;放;}//其他一些设置变量}}
现在要从不同的窗口引用此对象,您可以使用:((App)Application.Current).setting_1
I have class representing my AppSettings
I have Main
window and Settings
window.
Each window contains instance of object AppSettings
So these are two objects are different.
If object AppSettings
in Settings
window gets changed the changes not reflected in the AppSettings
of the Main
window.
IS there any way i can share AppSettings
object between windows so i have only one instance?
I've tried to create shared base class but got an error
Partial declarations of "class name" must not specify different base classes
I know this answer is bump to the topic but I found other easier way of doing what is asked so that could help anyone in future. In every WPF application there is app.xaml and app.xaml.cs created. So create a object of setting inside app.xaml.cs and it would look something like this :
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
}
}
Now to refer to this object from different window you can use : ((App)Application.Current).setting_1
这篇关于在 WPF 中的两个窗口之间共享同一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!