WPF ComboBox SelectionChanged event to command not firing
33,130
Solution 1
Bind SelectedValue
to a Property
on the view model.
In the Property
set{...}
block do your logic there or call
ListTypeComboSelectionChangedCmdExec(value)
See Binding ComboBox SelectedItem using MVVM
Solution 2
In my case, I use handler in the code behind and connect it to ModelView as below.
var viewModel = (MyViewModel)DataContext;
if (viewModel.MyCommand.CanExecute(null))
viewModel.MyCommand.Execute(null);
Please check this link: Call Command from Code Behind
Author by
Lucifer
Updated on July 09, 2022Comments
-
Lucifer almost 2 years
I have the following XAML of a
ComboBox
which has a code-behindSelectionChanged
event handler and another Command property of the ViewModel. I have set theSelectedIndex
property to 0. Now when I run the project, the code-behind handler is invoked, but theCommand
is not executed. What I want is that theCommand
should be executed forSelectedIndex=0
the first time the View is loaded.<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:
public ICommand ListTypeComboSelectionChangedCmd { get { return new RelayCommand<string>(ListTypeComboSelectionChangedCmdExec); } private set; }
ICommand Handler:
private void ListTypeComboSelectionChangedCmdExec(string listType) { }
-
Lucifer about 10 yearsThat's a smart solution, but I would have preferred to keep the setter clean. Also I was more interested in knowing as to why such a functionality doesn't work, where the SelectionChanged event fires but it does not execute the underlying Command. Thanks anyway.
-
Richard June over 7 yearsWhy not Bind SelectedValue to the Property, but in your view OnLoaded event handler, set it to the first value. Setter logic is sub optimal
-
Michal Ciechan about 6 years@Lucifer bit late of a reply, but my guess would be that the event gets fired before the behaviour gets 'Attached'.