2010-03-05 33 views
5

我有三個用戶控件。這裏是他們的描述: 1)第一個用戶控件(ucCountry)包含組合框,它顯示來自xml文件的國家名稱。Windows窗體應用程序,如何在自定義控件之間進行通信?

2)第二個用戶控件(ucChannelType)包含兩個單選按鈕,一個用於選擇TV,另一個用於選擇Radio Channel Type。

3)第三用戶控件(ucChannels)將填充其中的國家名稱是由ucCountry提供和類型由ucChannelType

提供現在,如何在這些形式的用戶控制之間進行通信的所有信道。我需要從表單中分離usercontrols。所以,我需要使用事件。但是,如果ucCountry觸發一個事件(比如說CountryChanged事件)並且ucChannels訂閱該事件,那麼如何從ucChannelType獲取通道類型。

在此先感謝...

回答

3

最好的解決方案是將屬性添加到您的自定義控件。在後臺可能沒有字段,獲取者只會從內部標準控制的屬性中獲取數據。

+0

+1這是微軟推薦的解決方案。 – 2010-03-05 18:49:22

+0

我沒有退出得到它,假設'control_A'有一個按鈕,'control_B'怎麼知道點擊'control_A'上的按鈕被點擊的時刻? – ThunderWiring 2016-10-12 13:54:39

+0

@ThunderWiring這是愚蠢的答案(我承認我寫了它)它並沒有真正回答這個問題,adharris的答案是正確的答案。 – Andrey 2016-10-12 14:01:35

2

您可以在ucCountry上提供當前選定國家/地區的房產。例如:

public Country SelectedCountry 
{ 
    get 
    { 
     return (Country) myComboBox.SelectedItem; 
    } 
} 

然後,當事件觸發時,其他控件將獲取屬性。

另一種選擇是使用自定義事件委託,所以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); 
0

您需要具有公共屬性s提供數據的控件,以及一個公共方法來註冊事件以用於控制消費數據。這裏有一個簡單的例子:

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); 
    } 
}