WPF ListBox.UnselectAll()不清除视觉状态

时间:2016-10-14 17:24:39

标签: c# wpf xaml listbox

我正在尝试构建一个ListBox,允许用户取消选择该项目。

这是我的XAML代码:

<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>

我的代码隐藏:

private void Speise_Gedrueckt(object sender, MouseButtonEventArgs e)
    {
       MyListBox.UnselectAll();
    }

我可以通过再次单击来取消选择该项目,它会将SelectedIndex设置为-1等,但它不会清除所选项目在ListBox本身中的边框。

我做了很多谷歌,但我发现没有改变这一事实。我试图设置通过style.setter选择的项目的边框/背景,但它也没有帮助。

2 个答案:

答案 0 :(得分:1)

注意Listbox项目有3种视觉状态 - 选中,未选中和聚焦。即使您通过代码隐藏取消选择列表框项目,键盘焦点仍然存在(假设您通过单击选择它)。这就是为什么会出现某种视觉指示器的原因。

答案 1 :(得分:0)

不确定何时要清除所选项目,因此我添加了一个带有EventHandler的按钮:

   <Button Width="100" Height="40" Click="Speise_Gedrueckt"></Button>

现在,当单击按钮时,将SelectedItem设置为null:

 private void Speise_Gedrueckt(object sender, RoutedEventArgs routedEventArgs)
 {
        MyListBox.SelectedItem = null;
 }