[英]How can I communicate between a windows forms application and a WebBrowser control
[英]Windows Forms application, how to communicate between custom controls?
我有三個用戶控件。 下面是它們的描述:1)第一個用戶控件(ucCountry)包含組合框,該組合框顯示xml文件中的國家/地區名稱。
2)第二個用戶控件(ucChannelType)包含兩個單選按鈕,一個用於選擇TV,另一個用於選擇Radio Channel Type。
3)第三個usercontrol(ucChannels)將填充ucCountry提供國家名稱和ucChannelType提供類型的所有通道
現在,如何以表格形式在這些用戶控件之間進行通信。 我需要將用戶控件與表單分離。 因此,我需要使用事件。 但是,如果ucCountry觸發一個事件(例如CountryChanged事件),而ucChannels訂閱了該事件,則如何從ucChannelType獲取通道類型。
提前致謝...
最好的解決方案是將屬性添加到自定義控件。 后台可能沒有字段,getter只會從內部標准控件的屬性中獲取數據。
您可以在ucCountry
上擁有一個提供當前所選國家/地區的屬性。 就像是:
public Country SelectedCountry
{
get
{
return (Country) myComboBox.SelectedItem;
}
}
然后,當事件觸發時,其他控件進入get屬性。
另一個選項是使用自定義事件委托,因此ucCountry.CountryChanged
的事件處理程序將具有國家/地區參數:
public delegate void CountryChangedDelegate(Country sender)
public event CountryChangedDelegate CountryChanged;
ucChannels中的事件處理程序:
public void ucCountry_CountryChanged(Country sender)
{
//do something with the new country
}
並將事件連接到ucChannels:
myUcCountry.CountryChanged += new CountryChangedDelegate(ucCountry_CountryChanged);
您需要具有用於提供數據的控件的公共屬性,並需要具有用於將事件注冊到使用數據的控件的公共方法。 這是一個簡單的示例:
public static void Test()
{
var a = new A();
var b = new B();
var c = new C() {a = a, b = b};
a.OnChange += c.Changed;
b.OnChange += c.Changed;
a.State = "CA";
b.ChannelType = "TV";
}
class A
{
private string _state;
public string State
{
get { return _state; }
set
{
_state = value;
if (OnChange != null) OnChange(this, EventArgs.Empty);
}
}
public event EventHandler<EventArgs> OnChange;
}
class B
{
private string _channelType;
public string ChannelType
{
get { return _channelType; }
set
{
_channelType = value;
if (OnChange != null) OnChange(this, EventArgs.Empty);
}
}
public event EventHandler<EventArgs> OnChange;
}
class C
{
public A a { get; set; }
public B b { get; set; }
public void Changed(object sender, EventArgs e)
{
Console.WriteLine("State: {0}\tChannelType: {1}", a.State, b.ChannelType);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.