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

查看:650
本文介绍了使用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天全站免登陆