2012-06-26 94 views
7

我有一個用戶控件有幾個按鈕,需要根據使用它的類採取不同的操作。處理WPF用戶控件的事件

問題是我不知道如何實現這些處理程序,因爲從最終應用程序使用我的用戶控件時,我沒有直接訪問按鈕來指定哪個處理程序處理哪些事件。

你會怎麼做?

回答

16

另一種方式做,這是揭露過的事件的事件在你的用戶控件:

public partial class UserControl1 : UserControl 
{ 
    public UserControl1() 
    { 
     InitializeComponent(); 
    } 


    public event RoutedEventHandler Button1Click; 

    private void button1_Click(object sender, RoutedEventArgs e) 
    { 
     if (Button1Click != null) Button1Click(sender, e);  
    } 
} 

這給你的用戶控件一個Button1Click事件掛接到你的控制範圍內的按鈕。

+0

謝謝你們倆,那些看起來很不錯的解決方案。還有更多的選擇嗎? –

4

我會爲每個「處理程序」的每個按鈕和委託創建一個命令。比你可以暴露委託給用戶(最終的應用程序),並在內部調用它們的方法在命令上的方法爲Execute()。例如:

public class MyControl : UserControl { 
     public ICommand FirstButtonCommand { 
      get; 
      set; 
     } 
     public ICommand SecondButtonCommand { 
      get; 
      set; 
     } 
     public Action OnExecuteFirst { 
      get; 
      set; 
     } 
     public Action OnExecuteSecond { 
      get; 
      set; 
     } 

     public MyControl() { 
      FirstButtonCommand = new MyCommand(OnExecuteFirst); 
      FirstButtonCommand = new MyCommand(OnExecuteSecond); 
     } 
    } 

對於cource,「MyCommand」需要實現ICommand。您還需要將您的命令綁定到相應的按鈕。希望這可以幫助。