我有一个提供 RelayCommand LoadImage 的 View 模型。
通常我会使用一个按钮并将命令绑定到这个按钮。
但是我想从 View 的代码隐藏中调用 LoadImage 命令(我需要做一些不能放入 View 模型的 View 相关的东西)
我知道的一种方法是为按钮创建一个事件处理程序,例如按钮_单击。
在 Button_Click 中,我会将 DataContext 转换为相应的 ViewModel 并使用此实例调用 (DataContext as MyViewModel).LoadImage.Execute(...)
这很奇怪,因为我需要知道 View 模型。
我正在尝试将 LoadImage 绑定(bind)到 View 中的资源而不是按钮,因此 Button_Click 事件只需要使用给定名称调用 FindResource 并将其转换为 ICommand 而无需知道特定的 ViewModel。
这可能吗?命令本身不是静态的,因为它需要知道它被调用的上下文。
最佳答案
您可以通过创建一个行为来实现它,这需要在您的项目中引用 Prism:
public class LoadImageBehavior : Behavior<Button>
{
public public static static readonly DependencyProperty CommandProperty =
DependencyProperty.Register("Command", typeof (ICommand), typeof (LoadImageBehavior));
public ICommand Command
{
get { return (ICommand) GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.Click += AssociatedObject_Click;
}
private void AssociatedObject_Click(object sender, RoutedEventArgs e)
{
//Logic...
if(Command != null && Command.CanExecute(null))
Command.Execute(null);
//Logic...
}
}
在 Xaml 上:
<Button>
<i:Interaction.Behaviors>
<Behaviors:LoadImageBehavior Command="{Binding LoadImageCommand}"/>
</i:Interaction.Behaviors>
</Button>
关于c# - 是否可以将命令绑定(bind)到资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17881320/