Home > Back-end >  WPF / C# , How to change the background color of the main window from another window?
WPF / C# , How to change the background color of the main window from another window?

Time:11-01

I wrote a WPF program where I want to change the background color of the main window using the settings window. Project requirements: 1- The settings window should be able to save the colors in a variable and display those colors again the moment the settings window is opened again. 2- The background color of the main window should be perfectly Binding to the colors in the settings window, which will be applied immediately when changes are made.

My WPF Project

I tried several methods including: 1- I defined a global variable of type LinearGradientBrush in the code behind the main window. 2- I defined a global variable of type LinearGradientBrush in the app.xaml file.

But none of these methods worked properly

CodePudding user response:

Why don't you :

1 - Open Settings
2 - When you close your settings (make 2 buttons Save and Cancel), this saves all parameters (I guess now you ask about colors, but there will be many parameters).
3 - Then in your main window, you will have that :

private void OpenSettings_Click(object sender, RoutedEventArgs e)
  {
       MySettings newWindow = new MySettings();
       if (newWindow.ShowDialog() == true)//set this.DialogResult=true in your Settings window.
       {
           this.updateAllParameters();
       }
  }

updateParameters() is just a function that will check all parameters (as backgroundcolor), then update them.

CodePudding user response:

In visual studio go to your Properties window. Navigate to settings, add a parameter of type color and give it a name like yourColor now if you change your color store it in the settings file:

properties.settings.default.yourColor = newBackgroundColor;
properties.settings.default.save();

wenn you start you window look in your properties and use it as background.

this.background = properties.settings.default.yourColor;

(pseudocode wont compile)

  • Related