WPF ComboBox SelectionChanged事件命令不触发

问题描述 投票:4回答:2

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

更新

代码隐藏事件处理程序:

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) { }
wpf mvvm combobox
2个回答
3
投票

在视图模型上将SelectedValue绑定到Property

Property set{...}区块做你的逻辑或打电话

ListTypeComboSelectionChangedCmdExec(value)

Binding ComboBox SelectedItem using MVVM


0
投票

这是一个很老的问题,但我会回答以后感兴趣的人。

在我的例子中,我在代码中使用处理程序并将其连接到ModelView,如下所示。

var viewModel = (MyViewModel)DataContext;
if (viewModel.MyCommand.CanExecute(null))
    viewModel.MyCommand.Execute(null);

请检查以下链接:Call Command from Code Behind

© www.soinside.com 2019 - 2024. All rights reserved.