kr13
kr13

Reputation: 537

Changing MainWindow background color WPF

I am trying to change the background color of the MainWindow using a dialogbox called EditColorDialog. The dialogbox can read the current background color of the main window just fine but I can't seem to get it to change that color.

public partial class EditColorDialog : Window
{
    ColorDialog colorPicker = new ColorDialog();  //this is a colorpicker
    MainWindow mw = new MainWindow();

    public ColorDialog()
    {
        InitializeComponent();
        rect.Fill = mw.background;  //reads the color off the main window
    }

    private void rect_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        colorPicker.Owner = this;
        if ((bool)colorPicker.ShowDialog())
        {
            //selects new color from colorpicker
            rect.Fill = new SolidColorBrush(colorPicker.SelectedColor);
        }
    }

    private void OkButton_Click(object sender, RoutedEventArgs e)
    {
        mw.background = rect.Fill;
        this.Close(); 
    }
}

I am using this property in the main window code

public Brush background
{
    get { return main_window.Background; }
    set { main_window.Background = value; }   
}

Upvotes: 1

Views: 11038

Answers (2)

dowhilefor
dowhilefor

Reputation: 11051

Why does you EditColorDialog contains another new MainWindow? I guess you want a reference to the existing MainWindow which opens the EditColorDialog not a new one.Also i guess thats what H.B. meant, is you have a property *b*ackground, but your MainWindow already contains a Property called *B*ackground notice the uppercase 'B'. When closing the Dialog you can now set the Background property in your passed MainWindow.

Upvotes: 1

brunnerh
brunnerh

Reputation: 184296

You create a new MainWindow every time you create such a dialog. Not a good idea.

If anything you should set the Application.MainWindow on application startup. Then set the reference like this:

MainWindow mw = (MainWindow)Application.Current.MainWindow;

and just use nw.Background, that property of yours seems like a non-static wrapper for a static call. Doing it this way you already have the main window.

Upvotes: 2

Related Questions