您的问题基本上归结为根据另一个表单的事件在一个表单上做某事。
在我看来,最好的方法是:
- 让
Main 自己执行所有操作。
- 让
FormA(和其他人)自己做所有的事情。
- 如果您需要根据
FormA 上发生的事件在Main 上做某事,让FormA 通知Main 那里发生了一些事情,所以去做你自己的事情吧。
- 如有必要,将数据从
FormA 传递到Main。
所以我会为此目的使用delegates。
在我的Main 中,我会声明一个带有这样签名的公共代表:
public delegate void NotifyComboBoxChange(string item);
也就是说,这个委托代表了一个方法,它接受一个string参数,并且返回类型为void。这个想法是让FormA“调用”Main 中的一个方法,并且该方法实质上通知组合框项目在FormA 上已更改。因此,如果我们有办法从FormA 调用驻留在Main 中的方法,那么我们就可以通知Main FormA 上发生的事件到目前为止还有我吗?
现在,如果我在Main 中编写这样的方法,并让它从FormA 调用,那应该可以实现我们的目标。这里,txtLabel 是TextBlock 中的Main。
public void ComboBoxValueChanged(string value)
{
txtLabel.Text = value;
}
要调用这样的方法,我将在Main 中定义一个NotifyComboBoxChange 类型的委托,如下所示,并向其注册ComboBoxValueChanged() 方法。您的 Main 代码应如下所示:
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();
}
}
因此,现在我们需要修改我们的FormA。当组合框选择发生变化时,我们需要告诉我们调用哪个委托。所以要做到这一点,我会像这样在FormA 的构造函数中传递委托:
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);
}
}