slider display not updated when value is changed by another window

I have a window with 2 buttons and a slider. button1 creates a new window and the button2 changes the slider value of the new window. But slider display not updated when button2 is clicked. What is wrong?

public Window1 newWindow1;
       
public MainWindow()
{
    InitializeComponent();
}

private void Button1_Click(object sender, RoutedEventArgs e)
{
    Window1 newWindow1 = new Window1();
    newWindow1.Show();
    newWindow1.mySlider.Value = 20;
}

private void Button2_Click(object sender, RoutedEventArgs e)
{
     newWindow1.mySlider.Value += 10;
}

1 answer

  • answered 2022-05-04 10:05 Mighty Badaboom

    In Button1_Click you are creating a local instance of the window instead using the field.

    Change your code like this.

    private void Button1_Click(object sender, RoutedEventArgs e)
    {
        newWindow1 = new Window1();
        newWindow1.Show();
        newWindow1.mySlider.Value = 20;
    }
    

    But I hardy recommend following the MVVM pattern when using WPF.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum