Reputation: 41
I'm trying to build a ListBox which allows the user to unselect the item.
This is my XAML code:
<ListBox Name="MyListBox"
ItemsSource="{Binding MoeglicheHauptspeisen}"
SelectionMode="Single">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Width="200"
Height="200"
Background="{StaticResource Braun}"
MouseDown="Speise_Gedrueckt">
<TextBlock Margin="0 50 0 0"
HorizontalAlignment="Center"
Text="{Binding SpeiseTyp}" />
<TextBlock HorizontalAlignment="Center" Text="{Binding Beschreibung}" />
<TextBlock HorizontalAlignment="Center" Text="{Binding Preis, StringFormat={}{0:C}}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And my code-behind:
private void Speise_Gedrueckt(object sender, MouseButtonEventArgs e)
{
MyListBox.UnselectAll();
}
I can unselect the item by clicking on it again, it does set SelectedIndex to -1 etc., but it doesn't clear the border that the selected item has in the ListBox itself.
I did google a lot but nothing I found did change that fact. I tried to set the border/background of the item which is selected via a style.setter, but it also didn't help.
Upvotes: 0
Views: 603
Reputation: 36
Pay attention that Listbox item has 3 visual states - Selected, Not selected, and Focused. Even if you deselect Listbox item through code-behind, keyboard focus will still be there (assuming that you selected it by clicking on it). That's why some kind of visual indicator will be shown.
Upvotes: 1
Reputation: 1193
Not sure when do you want to clear the selected item so I added a button with the EventHandler:
<Button Width="100" Height="40" Click="Speise_Gedrueckt"></Button>
Now set the SelectedItem to null when the button is clicked:
private void Speise_Gedrueckt(object sender, RoutedEventArgs routedEventArgs)
{
MyListBox.SelectedItem = null;
}
Upvotes: 0