Как я могу реализовать ICommandSource в WPF, чтобы мой пользовательский элемент управления мог использовать команду из xaml?

Не могли бы вы предоставить пример того, как вы реализуете интерфейс ICommandSource . Как я хочу, чтобы мой UserControl , который не имеет возможности указать команду в xaml, имел эту возможность. И чтобы иметь возможность обрабатывать команду, когда пользователь нажимает CustomControl .

11
задан akjoshi 4 December 2014 в 11:19
поделиться

2 ответа

Вот пример:

public partial class MyUserControl : UserControl, ICommandSource
{
    public MyUserControl()
    {
        InitializeComponent();
    }



    public ICommand Command
    {
        get { return (ICommand)GetValue(CommandProperty); }
        set { SetValue(CommandProperty, value); }
    }

    public static readonly DependencyProperty CommandProperty =
        DependencyProperty.Register("Command", typeof(ICommand), typeof(MyUserControl), new UIPropertyMetadata(null));


    public object CommandParameter
    {
        get { return (object)GetValue(CommandParameterProperty); }
        set { SetValue(CommandParameterProperty, value); }
    }

    // Using a DependencyProperty as the backing store for CommandParameter.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty CommandParameterProperty =
        DependencyProperty.Register("CommandParameter", typeof(object), typeof(MyUserControl), new UIPropertyMetadata(null));

    public IInputElement CommandTarget
    {
        get { return (IInputElement)GetValue(CommandTargetProperty); }
        set { SetValue(CommandTargetProperty, value); }
    }

    // Using a DependencyProperty as the backing store for CommandTarget.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty CommandTargetProperty =
        DependencyProperty.Register("CommandTarget", typeof(IInputElement), typeof(MyUserControl), new UIPropertyMetadata(null));


    protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
    {
        base.OnMouseLeftButtonUp(e);

        var command = Command;
        var parameter = CommandParameter;
        var target = CommandTarget;

        var routedCmd = command as RoutedCommand;
        if (routedCmd != null && routedCmd.CanExecute(parameter, target))
        {
            routedCmd.Execute(parameter, target);
        }
        else if (command != null && command.CanExecute(parameter))
        {
            command.Execute(parameter);
        }
    }

}

Обратите внимание, что свойство CommandTarget используется только для RoutedCommands

23
ответ дан 3 December 2019 в 04:51
поделиться

Ваш UserControl будет иметь код за файлом cs или vb, вам необходимо реализовать интерфейс ICommandSource, и как только вы это реализуете, в некоторых случаях вам придется фактически вызвать команду, а также проверить CanExecute.

0
ответ дан 3 December 2019 в 04:51
поделиться
Другие вопросы по тегам:

Похожие вопросы: