0

I have two windows(forms). In the first window I have a combobox, in the second window I have a button. How do I set the selectedindex of the combobox in windows 1 when the button in window 2 is clicked?

I have tried this without success:

in Window1:

public int OutputCombostr
    {
        get { return this.OutputCombo.SelectedIndex; }
        set { this.OutputCombo.SelectedIndex = value; }
    }

In Window2:

  private void Button_Click_2(object sender, RoutedEventArgs e)
            {
                MainWindow firstwindow = new MainWindow();

                firstwindow.OutputCombostr = 3;
            }
Omid
  • 823
  • 1
  • 11
  • 31
  • you don't happen to be using MVVM (Model View ViewModel). This would be so much easier if you are, but I'm figuring you are not. – DJ Burb Nov 15 '12 at 17:58

2 Answers2

1

You need to some how get a reference to the existing instance of your MainWindow class. If this is WPF and that window is indeed your start up object, then you should be able to access it via Application.MainWindow (rather than newing it up).

Alternatively, you might look into something like the event aggregator pattern. Here's a SO question that you could use as a starting point: Trying to understand the event aggregator pattern

Community
  • 1
  • 1
CodingGorilla
  • 19,612
  • 4
  • 45
  • 65
0

Using MVVM would be very useful to you, but also you may obtain a reference to the main window using this code: Application.Current.MainWindow or for getting all applictaion's windows: Application.Current.Windows.

For access to the combobox you need first give it a name in the xaml code: <ComboBox x:Name="comboBox">... And then, from the second window make a cast (Application.Current.MainWindow as MainWindow).comboBox.IsChecked supposing that your main window's class is name MainWindow. Also i think it is better to use the MVVM pattern to solve this.

Hope this could helps to you...

Raúl Otaño
  • 4,640
  • 3
  • 31
  • 65