我已经在winform中实现了一个wpf组合框,现在必须以某种方式让它在更改框时调用winform中的函数或事件,并且能够从winform中更改值。
主:
namespace main
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
ElementHost elhost = new ElementHost();
elhost.Size = new Size(174, 24);
elhost.Location = new Point(93,60);
MyWPFControl wpfctl = new MyWPFControl();
elhost.Child = wpfctl;
this.Controls.Add(elhost);
elhost.BringToFront();
}
public void status_change(int val)
{
MessageBox.Show("Box value has changed to:" + Convert.ToString(val) );
}
和wpf:
namespace main
{
/// <summary>
/// Interaction logic for MyWPFControl.xaml
/// </summary>
public partial class MyWPFControl : UserControl
{
public MyWPFControl()
{
InitializeComponent();
}
private void statComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
main.status_change(statComboBox.SelectedIndex);
/// says:
/// Error 1 The type or namespace name 'status_change' does not exist in the namespace 'main' (are you missing an assembly reference?) C:\Users\Robert\documents\visual studio 2010\Projects\XMPP\main\wpf_combo_status.xaml.cs 31 18 main
}
}
}
任何想法我可能做错了什么?谢谢!
答案 0 :(得分:2)
没有更多的上下文很难说,但似乎你想要的代码可能是:
private void statComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
main.status_change(statComboBox.SelectedIndex);
}
假设main
是您要呼叫Form1
的{{1}}个实例。
答案 1 :(得分:2)
在MyWPFControl
中公开一个事件,如:
public SelectionChangedEventArgs:EventArgs
{
public int SelectedIndex {get; private set;}
public SelectionChangedEventArgs (int selIdx)
{
this.SelectedIndex = selIdx;
}
}
public partial class MyWPFControl : UserControl
{
public event EventHandler<SelectionChangedEventArgs> SelectionChanged;
public MyWPFControl()
{
InitializeComponent();
}
private void statComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
OnSelectionChanged(statComboBox.SelectedIndex);
}
private void OnSelectionChanged(int selIdx)
{
if (SelectionChange != null)
SelectionChanged(this, new SelectionChangedEventArgs(selIdx));
}
}
然后在您的表单中订阅,例如:
public Form1()
{
InitializeComponent();
ElementHost elhost = new ElementHost();
elhost.Size = new Size(174, 24);
elhost.Location = new Point(93,60);
MyWPFControl wpfctl = new MyWPFControl();
elhost.Child = wpfctl;
this.Controls.Add(elhost);
elhost.BringToFront();
wpfctl.SelectionChanged += myWPFControls_SelectionChanged;
}
private void myWPFControls_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
status_change(e.SelectedIndex);
}
<强> P.S:强>
我无法测试它,所以可能会有一些错误,但只是为了给你一个想法...;)