I know it's late, but have you tried "ComboBox.SelectedItems.Clear"?
How to trigger SelectionChanged event when ComboBox selected Index is same not necessarily changed in WPF C#?
Hi there, I have a simple WPF application where a different window will open if I select the last item of a Combo box. my code is working successfully but there some issue on my code. I want some more functionality. Suppose, I select the last item, A window will appear. if I select the last item again then the another window will not appear again, that only works if I select another item after that again the last item.
I want to open that different window again and again by selecting the last item it does not matter if I select the last item, last time or not.
Here is my C# code in MainWindow.xaml.cs :
private void cmb1_SelectionChanged(object sender, SelectionChangedEventArgs e) {
Window1 win1 = new Window1();
if (cmb1.SelectedIndex == cmb1.Items.Count - 1)
{
win1.Show();
} else {
win1.Close();
}
}
Here I also tried by putting cmb1.SelectedIndex = -1;
after win1.Show();
. It works but it behaves abnormally that means my ComboBox became blank which I obviously don't want.
Here is my XAML code :
<Grid x:Name="Grid">
<ComboBox x:Name="cmb1" Width="400" Height="25" SelectionChanged="cmb1_SelectionChanged" >
<ComboBoxItem >item1</ComboBoxItem>
<ComboBoxItem>item2</ComboBoxItem>
<ComboBoxItem>item3</ComboBoxItem>
<ComboBoxItem>item4</ComboBoxItem>
</ComboBox>
</Grid>
My final approach is to Create a proper ViewModel and use DataBinding with simple properties instead. But I don't know How to do that in this scenario.
2 answers
Sort by: Most helpful
-
-
Hui Liu-MSFT 48,571 Reputation points Microsoft Vendor
2022-10-20T07:45:32.817+00:00 Using the MVVM code below can achieve the same effect as yours.
MainWindow.xaml:
<Window.DataContext> <local:ViewModel/> </Window.DataContext> <StackPanel x:Name="Grid"> <ComboBox Name="cb2" Width="400" Height="30" ItemsSource="{Binding List}" DisplayMemberPath="Name" SelectedValuePath="Name" SelectedIndex="{Binding Selected}"> </ComboBox> </StackPanel>
Codebehind:
252381-4444.txt----------------------------------------------------------------------------
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.