C# 在WPF中将多个参数(包括类型)传递给ViewModel

C# 在WPF中将多个参数(包括类型)传递给ViewModel,c#,wpf,xaml,imultivalueconverter,C#,Wpf,Xaml,Imultivalueconverter,如何将XAML中的两个参数,一个类型对象和一个模型{Binding}作为CommandParameter传递给ViewModel。我在SO上遇到过不同的帖子,但都使用控件绑定。有没有办法改为传递类型 我想要这样的东西: <MenuItem x:Key="RuleBase" Header="RuleBase" x:Shared="False" Command="{Binding DataContext.AddRuleCommand, RelativeSource={Relative

如何将XAML中的两个参数,一个类型对象和一个模型
{Binding}
作为CommandParameter传递给ViewModel。我在SO上遇到过不同的帖子,但都使用控件绑定。有没有办法改为传递类型

我想要这样的东西:

<MenuItem x:Key="RuleBase" Header="RuleBase" x:Shared="False" 
    Command="{Binding DataContext.AddRuleCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}">
    <MenuItem.CommandParameter>
        <MultiBinding Converter="{StaticResource MultiParameterConverter}">
            <Binding Path="{Binding}" />
            <Binding Path="{x:Type local:RuleBase}" />
        </MultiBinding>
    </MenuItem.CommandParameter>
</MenuItem>
<MenuItem CommandParameter="{Binding ConverterParameter={x:Type local:RuleBase}, 
                                     Converter={StaticResource YourConverter}}" />

这段代码仅使用一个参数:

<MenuItem x:Key="RuleBase" Header="RuleBase" x:Shared="False" 
    Command="{Binding DataContext.AddRuleCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
    CommandParameter="{x:Type local:RuleBase}" />

您可以在多重绑定中使用此绑定:

<MultiBinding Converter="{StaticResource MultiParameterConverter}">
    <Binding />
    <Binding Source="{x:Type local:RuleBase}" />
</MultiBinding>    

但是,由于类型不会更改,并且多重绑定表达式中只有一个真正的绑定,因此可以按如下方式重写:

<MenuItem x:Key="RuleBase" Header="RuleBase" x:Shared="False" 
    Command="{Binding DataContext.AddRuleCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}">
    <MenuItem.CommandParameter>
        <MultiBinding Converter="{StaticResource MultiParameterConverter}">
            <Binding Path="{Binding}" />
            <Binding Path="{x:Type local:RuleBase}" />
        </MultiBinding>
    </MenuItem.CommandParameter>
</MenuItem>
<MenuItem CommandParameter="{Binding ConverterParameter={x:Type local:RuleBase}, 
                                     Converter={StaticResource YourConverter}}" />

尝试将整个菜单项作为命令参数传递:

CommandParameter="{Binding RelativeSource={RelativeSource Self}}"

您必须使用可以接受参数的ICommand实现。

所以您发布的第一个代码块对您不起作用?因为我觉得没问题。除了您可能希望删除第一个
CommandParameter=“{x:Type local:RuleSet}”
之外,因为当您将它与
一起使用时,您将定义两次。您还可以发布您的多参数转换器吗?很抱歉出现了打字错误,我已更正并删除了第一个代码块中的单个命令参数。没有
{Binding}
是指与
MenuItem
@FSX关联的模型。您发布的第一个代码块有什么问题。在我看来这是一个有效的解决方案。。。没用吗?如果是这样,发布命令AddRuleCommand和multiparameterConverterHanks,但同时给出语法错误。如何克服它。只是删除了1个空格使它变短,很遗憾它不能变短(我不是说这回答了OP的问题-事实上我真的想否决它)。@FSX:我没有在源属性中使用绑定。@Liero,我不明白你的第二点,类型不会改变,在多重绑定表达式中只有一个真正的绑定。这意味着什么?在我的第一个代码示例中,有一个绑定到DataContext,另一个绑定到类型。但是您不必绑定到类型,因为
RuleBase
仍将是相同的
RuleBase
。第二个绑定永远不会更改最终值。因此,该类型可以作为ConverterParameter传递给转换器,就像我在第二个代码示例中所做的那样。但是,DataContext可以更改(或者在不同的地方可以不同)。因此,只有一种绑定是有意义的。