WPF ComboBox Mvvm绑定

时间:2015-04-17 11:28:44

标签: c# wpf mvvm

我试图从列表中选择值到命令中。有没有简单的方法将命令参数绑定到所选项?

<ComboBox HorizontalAlignment="Left" Margin="-56,10,0,0" VerticalAlignment="Top" Width="120" SelectedIndex="0" ItemsSource="{Binding Time}">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Loaded">
                <i:InvokeCommandAction Command="{Binding TestCommand}" CommandParameter="{Binding }"></i:InvokeCommandAction>
            </i:EventTrigger>
            <i:EventTrigger EventName="SelectionChanged">
                <i:InvokeCommandAction Command="{Binding TestCommand}" CommandParameter="{Binding }"></i:InvokeCommandAction>
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </ComboBox>

当我尝试类似

的时候
                <i:EventTrigger EventName="SelectionChanged">
                <i:InvokeCommandAction Command="{Binding TestCommand}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ComboBox}},Path=SelectionBoxItem}"></i:InvokeCommandAction>
            </i:EventTrigger>

奇怪的是为什么?

1 个答案:

答案 0 :(得分:0)

<ComboBox x:Name="Combo" HorizontalAlignment="Left" Margin="-56,10,0,0" VerticalAlignment="Top" Width="120" SelectedIndex="0" ItemsSource="{Binding Time}">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Loaded">
                <i:InvokeCommandAction Command="{Binding TestCommand}" CommandParameter="{Binding ElementName=Combo, Path=SelectedItem}"></i:InvokeCommandAction>
            </i:EventTrigger>
            <i:EventTrigger EventName="SelectionChanged">
                <i:InvokeCommandAction Command="{Binding TestCommand}" CommandParameter="{Binding }"></i:InvokeCommandAction>
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </ComboBox>

如果您为组合框命名,则可以使用ElementName绑定并绑定到路径SelectedItem