wpf eventsetter handler binding in style

后端 未结 3 1525
刺人心
刺人心 2020-12-14 02:51

I have a style, and I want to bind a command to the EventSetter\'s Handler with RelativeSource. The command is in the viewModel.

相关标签:
3条回答
  • 2020-12-14 03:17

    My answer on this question does the trick without any external tool kits/libraries. However, it does not use RelativeSource, and it is not 100% MVVM. It requires one line of code in a code-behind event handler.

    0 讨论(0)
  • 2020-12-14 03:33

    As you are using MVVM, I suggest you Galasoft MVVM Light Toolkit EventToCommand

    0 讨论(0)
  • 2020-12-14 03:41

    Right now you are binding the MouseLeftButtonDown Event to TextBlock.TextBlockMouseLeftButtonDownCommand. TextBlockMouseLeftButtonDownCommand is not a valid property for a TextBlock, nor does it sound like it's an Event Handler.

    I use the AttachedCommandBehavior all the time in styles for hooking up a Command to an Event. The syntax usually looks like this (note the DataContextin the Command Binding):

    <Style x:Key="ItemTextBlockEventSetterStyle" TargetType="{x:Type TextBlock}">
        <Setter Property="local:CommandBehavior.Event" Value="MouseLeftButtonDown" />
        <Setter Property="local:CommandBehavior.Command"
                Value="{Binding DataContext.TextBlockMouseLeftButtonDownCommand, 
                                RelativeSource={RelativeSource Self}}" />
    </Style>
    

    The alternative is to hook the EventSetter up to an event in the code-behind, and process the command from there:

    <Style x:Key="ItemTextBlockEventSetterStyle" TargetType="{x:Type TextBlock}">
        <EventSetter Event="MouseLeftButtonDown" 
                     Handler="TextBlockMouseLeftButtonDown"/>
    </Style>
    

    Event handler in code behind...

    void TextBlockMouseLeftButtonDown(object sender, MouseEventArgs e)
    {
        var tb = sender as TextBlock;
        if (tb != null)
        {
            MyViewModel vm = tb.DataContext as MyViewModel;
    
            if (vm != null && TextBlockMouseLeftButtonDownCommand != null
                && TextBlockMouseLeftButtonDownCommand.CanExecute(null))
            {
                vm.TextBlockMouseLeftButtonDownCommand.Execute(null)
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题