ListBox: Item selected is not highlighted

淺唱寂寞╮ 提交于 2019-12-12 15:59:22

问题


In my WPF application, I have a simple listbox:

                 <ListBox x:Name="lbUtilities">
                    <ListBoxItem Tag="2" Content="One" IsSelected="True" />
                    <ListBoxItem Tag="5" Content="Two" />
                 </ListBox>

The problem is that when the ListBox appears first time, the selected item ("One") is not highlighted. If I click on any item, it gets highlighted. How could I have the selected by default item to be highlighted to the system color?

Thanks.


回答1:


It is selected but you need a hightlight for not focused

<ListBox Grid.Row="0" x:Name="lbUtilities">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True" >
                    <Setter Property="FontWeight" Value="Bold" />
                    <Setter Property="Background" Value="Transparent" />
                    <Setter Property="Foreground" Value="Black" />
                </Trigger>
            </Style.Triggers>
            <Style.Resources>
                <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black"/>
                <!-- Background of selected item when focussed -->
                <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="LightCyan"/>
                <!-- Background of selected item when not focussed -->
                <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="LightGray" />
            </Style.Resources>
        </Style>
    </ListBox.ItemContainerStyle>
    <ListBoxItem Tag="2" Content="One" IsSelected="True"/>
    <ListBoxItem Tag="5" Content="Two" />
</ListBox>



回答2:


<Grid FocusManager.FocusedElement="{Binding ElementName=lbUtilities}">
    <ListBox Name="lbUtilities" SelectedIndex="0" >
        <ListBoxItem Content="One"></ListBoxItem>
        <ListBoxItem Content="Two"></ListBoxItem>
    </ListBox>
</Grid>



回答3:


I had a similar problem with the listview control where the selected item was highlighted only from user clicking on it, not from code behind such as:

MyListView.SelectedItem = SomeObjectInItemsSource

I saw that the item was effectively selected but not highlighted as defined in my ItemContainerStyle. Then i tried something else:

With CType(MyListView.ItemsSource,IList) 
    .MyListView.SelectedIndex = .IndexOf(SomeObjectInItemsSource)
End With

then it started to work just as expected.



来源:https://stackoverflow.com/questions/17725488/listbox-item-selected-is-not-highlighted

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!