Sharing the same object between two windows in WPF

This article introduces the processing method of sharing the same object between two windows in WPF, which has certain reference value for everyone to solve the problem. Friends who need it, follow the editor to learn together!
Problem Description
I have class that represents my AppSettings I have Main window and Settings window.

Each window contains the object AppSettings

So
these are two different objects. If the object AppSettings in the Settings window changes, the changes are not reflected in the AppSettings in the Main window. >

Is there any way I can share the AppSettings object between windows so I only have one instance?

I try to create a shared base class but I get the error

A partial declaration of a class name" cannot specify a different base class
Solution
I know this answer is off topic, but I found other easier ways to do what was asked so that may help anyone in the future. In every WPF In the application, both app.xaml and app.xaml.cs are created. So create a settings object in app.xaml.cs, which looks like this:

namespace WpfApplication { public section class App:Application { // settings: public int setting_1 { get; put; } // some setting variables public string setting_2 { get; put; } // some other setting variables }} now
want To refer to this object from a different window you can use: ((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

That concludes this article on sharing the same object between two windows in WPF,

The actual use is as follows:
insert image description here
insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/weixin_41883890/article/details/128816983