【问题标题】:Handling events of WPF User Control处理 WPF 用户控件的事件
【发布时间】:2012-06-27 16:10:22
【问题描述】:

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

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

你会怎么做?

【问题讨论】:

    标签: c# wpf events user-controls


    【解决方案1】:

    另一种方法是通过 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 事件,该事件与您控件中的该按钮挂钩。

    【讨论】:

    • 谢谢你们,这些似乎是不错的解决方案。还有其他选择吗?
    【解决方案2】:

    我将为每个按钮创建一个命令并为每个“处理程序”委托。比您可以向用户(最终应用程序)公开代表并在命令的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。您还需要将命令绑定到相应的按钮。希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2010-10-04
      • 2010-12-26
      • 1970-01-01
      • 2010-09-10
      • 2011-01-30
      • 1970-01-01
      • 2015-02-02
      • 2011-02-25
      • 1970-01-01
      相关资源
      最近更新 更多