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
WPF ComboBox SelectionChanged event to command not firing
提问by Lucifer
I have the following XAML of a ComboBox
which has a code-behind SelectionChanged
event handler and another Command property of the ViewModel. I have set the SelectedIndex
property to 0. Now when I run the project, the code-behind handler is invoked, but the Command
is not executed. What I want is that the Command
should be executed for SelectedIndex=0
the 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 SelectedValue
to a Property
on the view model.
绑定SelectedValue
到Property
视图模型上的a 。
In the Property
set{...}
block do your logic there or call
在Property
set{...}
块中做你的逻辑或调用
ListTypeComboSelectionChangedCmdExec(value)
回答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
请检查此链接:从代码隐藏调用命令