Your problem essentially boils down to doing something on one form based on the events of another form.
The best approach to do this is, in my opinion:
- Let
Main
do all its own actions.
- Let
FormA
(and others) do all its own actions.
- If you need to do something on
Main
based on an event that occurred on FormA
, let FormA
notify Main
that something happened there, so go do your own thing.
- If necessary, pass data from
FormA
to Main
.
So I would make use of delegates for this purpose.
In my Main
I'd declare a public delegate with a signature like this:
public delegate void NotifyComboBoxChange(string item);
That is, this delegate represents a method that takes in one string
parameter, and has void return type. The idea is to let FormA
'call' a method in Main
, and that method essentially notifies the combo box item was changed on FormA
. So, if there was a way for us to call a method that resides in the Main
from FormA
, we can then notify Main
of an event happening on FormA
With me so far?
Now, if I write a method like this in the Main
, and let it be called from FormA
, that should accomplish our goal. Here, txtLabel
is a TextBlock
in Main
.
public void ComboBoxValueChanged(string value)
{
txtLabel.Text = value;
}
To call such a method, I would define a delegate of type NotifyComboBoxChange
in Main
like below, and register the ComboBoxValueChanged()
method to it. Your Main
code behind should look like this:
public delegate void NotifyComboBoxChange(string item);
public partial class Form1 : Window
{
public NotifyComboBoxChange notifyDelegate;
FormA formA = null;
public Form1()
{
InitializeComponent();
// This is 'registering' the ComboBoxValueChanged method to the delegate.
// So, when the delegate is invoked (called), this method gets executed.
notifyDelegate += new NotifyComboBoxChange(ComboBoxValueChanged);
}
public void ComboBoxValueChanged(string value)
{
txtLabel.Text = value;
}
private void btnOpen_Click(object sender, RoutedEventArgs e)
{
// Passing the delegate to `FormA`
formA = new FormA(notifyDelegate);
formA.Show();
}
}
Accordingly, now we need to modify our FormA
. We need to tell us which delegate to invoke when the combo box selection change happens. So to do that, I'd pass the delegate in the constructor of FormA
like so:
public partial class FormA : Window
{
NotifyComboBoxChange notifyDel;
public FormA(NotifyComboBoxChange notify)
{
InitializeComponent();
notifyDel = notify;
}
private void cmbItems_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// This gets the currently selected value in the CombBox
var value = cmbItems.SelectedValue.ToString();
// This invokes the delegate, which in turn calls the ComboBoxValueChanged() method in Main.
notifyDel?.Invoke(value);
}
}