WPF ComboBox SelectionChanged事件命令不触发

我有一个ComboBox的XAML,它有一个代码隐藏的SelectionChanged事件处理程序和ViewModel的另一个Command属性.我已将SelectedIndex属性设置为0.现在,当我运行项目时,将调用代码隐藏处理程序,但不执行Command.我想要的是在第一次加载View时应该为SelectedIndex = 0执行Command.

<ComboBox Name="listComboBox" SelectionChanged="listComboBox_SelectionChanged" SelectedIndex="0" SelectedValuePath="Content" Margin="5,0" Height="35" Width="150" VerticalAlignment="Center" HorizontalAlignment="Left">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <i:InvokeCommandAction Command="{Binding ListTypeComboSelectionChangedCmd}" CommandParameter="{Binding ElementName=listComboBox, Path=SelectedValue}"/>
        </i:EventTrigger>
     </i:Interaction.Triggers>
     <ComboBoxItem Content="ItemOne" />
     <ComboBoxItem Content="ItemTwo" />
     <ComboBoxItem Content="ItemThree" />
</ComboBox>

更新

代码隐藏事件处理程序:

private void listComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { }

ICommand对象:

public ICommand ListTypeComboSelectionChangedCmd 
{ 
    get { return new RelayCommand<string>(ListTypeComboSelectionChangedCmdExec); }
    private set;
}

ICommand Handler:

private void ListTypeComboSelectionChangedCmdExec(string listType) { }

最佳答案 将SelectedValue绑定到视图模型上的Property.

在Property set {…}块中,在那里做你的逻辑或调用

ListTypeComboSelectionChangedCmdExec(value)

Binding ComboBox SelectedItem using MVVM

点赞