WPF ComboBox SelectionChanged 事件到命令不触发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22619114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:04:46  来源:igfitidea点击:

WPF ComboBox SelectionChanged event to command not firing

wpfmvvmcombobox

提问by Lucifer

I have the following XAML of a ComboBoxwhich has a code-behind SelectionChangedevent handler and another Command property of the ViewModel. I have set the SelectedIndexproperty to 0. Now when I run the project, the code-behind handler is invoked, but the Commandis not executed. What I want is that the Commandshould be executed for SelectedIndex=0the first time the View is loaded.

我有以下 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>

Update

更新

Code-behind event handler:

代码隐藏事件处理程序:

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

ICommand object:

ICommand 对象:

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

ICommand Handler:

ICommand 处理程序:

private void ListTypeComboSelectionChangedCmdExec(string listType) { }

采纳答案by Michal Ciechan

Bind SelectedValueto a Propertyon the view model.

绑定SelectedValueProperty视图模型上的a 。

In the Propertyset{...}block do your logic there or call

Propertyset{...}块中做你的逻辑或调用

ListTypeComboSelectionChangedCmdExec(value)

See Binding ComboBox SelectedItem using MVVM

请参阅使用 MVVM 绑定 ComboBox SelectedItem

回答by Sangwon Choi

This is really old question, but I'll answer for anyone who are interested later.

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

In my case, I use handler in code behind and connect it to ModelView as below.

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

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

Please check this link: Call Command from Code Behind

请检查此链接:从代码隐藏调用命令