【问题标题】:Command Binding to Routed Event in WPF User-control在 WPF 用户控件中绑定到路由事件的命令
【发布时间】:2013-02-11 11:40:37
【问题描述】:

我想将 Viewmodel 命令绑定到用户控件的路由事件。 这是我所拥有的详细说明。

我有一个用户控件,其中有一个 Image(显示图像)和一个 Button 在底部(Button 删除 Image)。我在ListView 中使用用户控件。

在我的用户控件代码后面我有一个RoutedEventHandler 来删除Image

public event RoutedEventHandler RemoveImage;

在我使用这个用户控件的窗口中,我放了:

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

如果我删除图像的代码在代码后面,则此代码可以正常工作。但我想将 Viewmodel 的命令绑定到 RemoveImage RoutedEvent。

可能喜欢(不正确)

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

如何做到这一点?

我找到了与RoutedCommandDependancyProperty 相关的东西,但找不到任何合适的方法,如何使用它们。

如果我需要进一步澄清我的问题,请告诉我。 感谢期待。

【问题讨论】:

  • 你使用任何 MVVM 框架吗?
  • 是的,我有经典的 MVVM。
  • 嗨,我不认为你可以通过 MVVM 使用命令来实现这一点,直到 itemesource 不在 VM 中。我的意思是使用命令删除图像,您需要将图像绑定到 VM 中的图像控件
  • 嗨哈迪克,看看AttachedCommandBehaviors它对我有用。

标签: wpf mvvm user-controls wpf-controls commandbinding


【解决方案1】:

您好,这段代码展示了如何调用命令: 命令处理程序

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);
    }
}

视图模型

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
    } 
}

查看

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

您需要将两个参数传递给 CommandHandler 构造函数,一个是您要在 Command 上触发的 Action,第二个参数是必须返回 bool 的 func。如果 func 仅计算为 true,则触发 Action。在上面的例子中,action 和 func 中的参数是您将绑定到 CommandParameter 的内容,因为我没有绑定 CommandParameter。我希望这会有所帮助。

【讨论】:

  • 感谢发帖,我需要将命令绑定到用户控件的自定义路由事件,即。我需要在调用“RemoveImage”自定义事件时调用命令。
  • 您在 .cs 中有事件,在 .cs 中有处理程序,那么为什么您希望它通过 Command.Search 处理网络上的中继命令,它们允许您通过 Command.but 将事件绑定到 VM你将在 VM 中拥有处理程序。
猜你喜欢
  • 2011-08-18
  • 2012-06-11
  • 2014-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-21
相关资源
最近更新 更多