2012-06-26 92 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。您还需要将您的命令绑定到相应的按钮。希望这可以帮助。