以样式添加事件处理程序

时间:2011-05-26 11:08:27

标签: silverlight

我的silverlight应用程序上有8个HyperlinkBut​​ton。 我想在单击每个方法时调用方法HyperlinkBut​​tonClick_Event。

我可以在风格上做吗? 如果“不”,那么如果不在每个HyperlinkBut​​ton实例上显式添加方法,我怎么能这样做呢?

2 个答案:

答案 0 :(得分:2)

如何在你的风格中使用这样的东西:

<Setter Property="Command" Value="{Binding ClickCommand}" />

使用Command(例如DelegateCommand)和Execute操作替换HyperlinkBut​​tonClick_Event代码。 这显然也要求你为每个按钮正确设置datacontext ...

DelegateCommand以非常最简单的形式:

public class DelegateCommand : ICommand
{
    private Func<object, bool> canExecute;
    private Action<object> executeAction;

    public DelegateCommand(Action<object> execute, Func<object, bool> canExecute)
    {
        this.executeAction = execute;
        this.canExecute = canExecute;
    }
    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        this.executeAction(parameter);
    }
    public bool CanExecute(object parameter)
    {
        return this.canExecute(parameter);
    }
}

你可以在任何地方找到这种实现,从SO到MSDN ......

答案 1 :(得分:1)

public class MyCheckBox : CheckBox
{
    public MyCheckBox()
    {
        this.Click += new RoutedEventHandler(MyCheckBox_Click);    
    }

    void MyCheckBox_Click(object sender, RoutedEventArgs e)
    {
        CheckBox chk = (sender as CheckBox);
    }
}

<foo:mycheckbox ................/>

定义自己的类并在样式文件中使用foo:mycheckbox。