【发布时间】:2012-06-27 16:10:22
【问题描述】:
我有一个带有多个按钮的用户控件,它们需要根据使用它的类采取不同的操作。
问题是我不知道如何实现这些处理程序,因为在最终应用程序中使用我的用户控件时,我无法直接访问按钮来指定哪个处理程序处理哪些事件。
你会怎么做?
【问题讨论】:
标签: c# wpf events user-controls
我有一个带有多个按钮的用户控件,它们需要根据使用它的类采取不同的操作。
问题是我不知道如何实现这些处理程序,因为在最终应用程序中使用我的用户控件时,我无法直接访问按钮来指定哪个处理程序处理哪些事件。
你会怎么做?
【问题讨论】:
标签: c# wpf events user-controls
另一种方法是通过 UserControl 中的事件公开事件:
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 事件,该事件与您控件中的该按钮挂钩。
【讨论】:
我将为每个按钮创建一个命令并为每个“处理程序”委托。比您可以向用户(最终应用程序)公开代表并在命令的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);
}
}
当然,“MyCommand”需要实现 ICommand。您还需要将命令绑定到相应的按钮。希望这会有所帮助。
【讨论】: