使用 WPF 绑定传递两个命令参数 [英] Passing two command parameters using a WPF binding

查看:80
本文介绍了使用 WPF 绑定传递两个命令参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个命令,我正在使用以下标准语法从我的 XAML 文件中执行该命令:

I have a command which I am executing from my XAML file using the following standard syntax:

<Button Content="Zoom" Command="{Binding MyViewModel.ZoomCommand}"/>

这很有效,直到我意识到我需要视图中的两条信息才能使此操作按照用户期望的方式完成(特别是画布的宽度和高度).

This worked fine until I realized that I needed TWO pieces of information from the view in order to make this operation complete the way users expect (the width and height of the canvas specfically).

似乎可以将数组作为参数传递给我的命令,但我认为没有办法在 CommandParameter 中指定与我的两个画布属性的绑定:

It seems like it's possible to pass an array as an argument to my command, but I don't see there being a way to specify the binding to my two canvas properties in the CommandParameter:

<Button Content="Zoom" 
        Command="{Binding MyViewModel.ZoomCommand" 
        CommandParameter="{Binding ElementName=MyCanvas, Path=Width}"/>

如何将宽度和高度都传递给我的命令?使用来自 XAML 的命令似乎不可能实现这一点,我需要在我的代码隐藏中连接一个单击处理程序,以便将此信息传递给我的缩放方法.

How do I pass both Width and Height to my command? It doesn't seem like this is possible using commands from XAML and I need to wire up a click handler in my codebehind to get this information to pass to my zoom method.

推荐答案

首先,如果您正在使用 MVVM,您通常会通过与视图绑定的单独属性将这些信息提供给您的 VM.这样您就不必将任何参数传递给您的命令.

Firstly, if you're doing MVVM you would typically have this information available to your VM via separate properties bound from the view. That saves you having to pass any parameters at all to your commands.

但是,您也可以多重绑定并使用转换器来创建参数:

However, you could also multi-bind and use a converter to create the parameters:

<Button Content="Zoom" Command="{Binding MyViewModel.ZoomCommand">
    <Button.CommandParameter>
        <MultiBinding Converter="{StaticResource YourConverter}">
             <Binding Path="Width" ElementName="MyCanvas"/>
             <Binding Path="Height" ElementName="MyCanvas"/>
        </MultiBinding>
    </Button.CommandParameter>
</Button>

在您的转换器中:

public class YourConverter : IMultiValueConverter
{
    public object Convert(object[] values, ...)
    {
        return values.Clone();
    }

    ...
}

然后,在您的命令执行逻辑中:

Then, in your command execution logic:

public void OnExecute(object parameter)
{
    var values = (object[])parameter;
    var width = (double)values[0];
    var height = (double)values[1];
}

这篇关于使用 WPF 绑定传递两个命令参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆