繁体   English   中英

处理WPF用户控件的事件

[英]Handling events of WPF User Control

我有一个带有几个按钮的用户控件,根据使用它的类需要采取不同的操作。

问题是我不知道如何实现这些处理程序,因为当从最终应用程序使用我的用户控件时,我没有直接访问按钮来指定哪个处理程序处理哪些事件。

你会怎么做?

另一种方法是通过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);     
    }
}

这为您的usercontrol提供了一个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);
        }
    }

对于cource,“MyCommand”需要实现ICommand。 您还需要将命令绑定到相应的按钮。 希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM