Command Binding to Routed Event in WPF User-contro

2019-07-21 21:57发布

问题:

I want to bind Viewmodel command to Usercontrol's Routed Event. Here is the detailed explanation of what I have.

I have a User Control which have one Image (which shows image) and one Button at bottom (Button to remove Image). I am using a Usercontrol in a ListView.

In my Usercontrol's Code behind I have a RoutedEventHandler to remove the Image:

public event RoutedEventHandler RemoveImage;

In the window where I use this Usercontrol, I have put:

<uc:ucImageListItem x:Name="ImageListItem" RemoveImage="ImageListItem_RemoveImage"  />

This code works correctly if My code to remove image is in code behind. but I want to Bind command of Viewmodel to RemoveImage RoutedEvent.

Probably like (not correct)

<uc:ucImageListItem x:Name="ImageListItem" RemoveImage="{binding CommandtoRemove}"  />

How to achieve this?

I found something related to RoutedCommand or DependancyProperty, but could not find any proper way, How to use them.

Let me know if I need to further clear my question. Thanks in anticipation.

回答1:

Hi this piece of code shows how to call command: Command handler

public class CommandHandler : ICommand
{
    public CommandHandler(Action<object> action,Func<object,bool> canexecute)
    {
        _action = action;
        _canExecute = canexecute;

    }
    Action<object> _action;
    Func<object, bool> _canExecute;

    public bool CanExecute(object parameter)
    {
       return _canExecute(parameter);
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        _action(parameter);
    }
}

ViewModel

public class MainViewModel
{
    private CommandHandler _buttonCommand;

    public CommandHandler ButtonCommand
    {
        get
        {
            return _buttonCommand ?? (_buttonCommand = new CommandHandler((param) => OnButtonCommand(param),(param)=>true));
        }
    }

    private void OnButtonCommand(object obj)
    {
        //DO things here whatever you want to do on Button click
    } 
}

View

<Button Command="{Binding ButtonCommand}" Content="ok"/>

you need to pass two parameters to CommandHandler Constructor one is Action that you want to fire on Command and second param is func that must return bool. If func evaluates to true only then the Action of Command is fired.And the param in action and func is what you will bind to the CommandParameter in my case above it will be null as I havent binded the CommandParameter.I hope this will help.