2015-10-14 513 views
1

如何將兩個參數從XAML(一個Type對象和一個Model {Binding})傳遞給ViewModel作爲CommandParameter。我遇到過不同的帖子,但都使用控制綁定。有沒有什麼方法可以傳遞Type。將多個參數(包括類型)傳遞給WPF中的ViewModel

我想是這樣的:

<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 x:Key="RuleBase" Header="RuleBase" x:Shared="False" 
    Command="{Binding DataContext.AddRuleCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" 
    CommandParameter="{x:Type local:RuleBase}" /> 
+0

那麼你發佈的第一個代碼塊並不適合你?因爲它看起來對我很好。除了你可能想要刪除第一個'CommandParameter =「{x:Type local:RuleSet}」',因爲當你將它與' ...一起使用時,你定義了兩次。你還可以發佈你的MultiParameterConverter嗎? –

+0

對不起,有錯字,我已經糾正並從第一個代碼塊中刪除單個命令參數。 –

+0

沒有'{Binding}'指的是與'MenuItem'關聯的模型。 –

回答

2

您可以使用此綁定在multibinding:

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

但由於Type不會改變,並且在多重綁定表達式中只有一個真正的綁定,所以它可以被重寫像這樣:

<MenuItem CommandParameter="{Binding ConverterParameter={x:Type local:RuleBase}, 
            Converter={StaticResource YourConverter}}" /> 
+0

感謝但'也給語法錯誤。如何克服它。 –

+0

只是刪除了1個空格,使其更短,可惜它不能更短(我不是說這回答了OP的問題 - 實際上是真的想降低這個)。 –

+0

@FSX:我沒有在Source屬性中使用綁定。 – Liero

-1

試圖通過整個菜單項爲命令參數:

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

你必須使用一個ICommand的實現,可以採取的參數。