gpt4 book ai didi

wpf - 在 WPF 用户控件中绑定(bind)到路由事件的命令

转载 作者:行者123 更新时间:2023-12-03 10:20:05 26 4
gpt4 key购买 nike

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

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

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

public event RoutedEventHandler RemoveImage;

在我使用这个用户控件的窗口中,我放了:
<uc:ucImageListItem x:Name="ImageListItem" RemoveImage="ImageListItem_RemoveImage"  />

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

可能喜欢(不正确)
<uc:ucImageListItem x:Name="ImageListItem" RemoveImage="{binding CommandtoRemove}"  />

如何做到这一点?

我发现了与 RoutedCommand 相关的内容或 DependancyProperty ,但找不到任何正确的方法,如何使用它们。

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

最佳答案

嗨,这段代码显示了如何调用命令:
命令处理程序

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 中的参数是您将绑定(bind)到 CommandParameter 的内容,因为我没有绑定(bind) CommandParameter。我希望这会有所帮助。

关于wpf - 在 WPF 用户控件中绑定(bind)到路由事件的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15082045/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com