WPF ComboBox SelectionChanged事件命令不触发

时间:2014-03-24 19:42:36

标签: wpf mvvm combobox

我有一个ComboBox的XAML,它有一个代码隐藏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>

更新

代码隐藏事件处理程序:

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) { }

2 个答案:

答案 0 :(得分:2)

SelectedValue绑定到视图模型上的Property

Property set{...}区块中执行您的逻辑或致电

ListTypeComboSelectionChangedCmdExec(value)

请参阅Binding ComboBox SelectedItem using MVVM

答案 1 :(得分:0)

这确实是个老问题,但是以后我会回答任何有兴趣的人。

在我的情况下,我在后面的代码中使用处理程序,并按如下所示将其连接到ModelView。

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

请检查此链接:Call Command from Code Behind