WPF ComboBox SelectionChanged事件导致命令不触发

Luc*_*fer 5 wpf combobox mvvm

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

<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>
Run Code Online (Sandbox Code Playgroud)

更新资料

代码隐藏事件处理程序:

<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>
Run Code Online (Sandbox Code Playgroud)

ICommand对象:

private void listComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { }
Run Code Online (Sandbox Code Playgroud)

ICommand处理程序:

public ICommand ListTypeComboSelectionChangedCmd 
{ 
    get { return new RelayCommand<string>(ListTypeComboSelectionChangedCmdExec); }
    private set;
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*han 7

绑定SelectedValue到Property视图模型上的a 。

在Property set{...}块中做你的逻辑或调用

ListTypeComboSelectionChangedCmdExec(value)
Run Code Online (Sandbox Code Playgroud)

请参阅使用 MVVM 绑定 ComboBox SelectedItem

  • 这是一个聪明的解决方案,但我更愿意保持二传手清洁。此外,我更想知道为什么这样的功能不起作用,其中 SelectionChanged 事件触发但它不执行底层命令。不管怎么说,还是要谢谢你。 (5认同)