4

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.

4

3 回答 3

4

它已被选中,但您需要突出显示不专注

<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>
于 2013-07-18T13:59:35.947 回答
-1
<Grid FocusManager.FocusedElement="{Binding ElementName=lbUtilities}">
    <ListBox Name="lbUtilities" SelectedIndex="0" >
        <ListBoxItem Content="One"></ListBoxItem>
        <ListBoxItem Content="Two"></ListBoxItem>
    </ListBox>
</Grid>
于 2013-07-18T14:35:09.317 回答
-1

我在 listview 控件中遇到了类似的问题,其中选定的项目仅通过用户单击突出显示,而不是来自后面的代码,例如:

MyListView.SelectedItem = SomeObjectInItemsSource

我看到该项目已被有效选择,但没有像我的 ItemContainerStyle 中定义的那样突出显示。然后我尝试了别的东西:

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

然后它开始按预期工作。

于 2016-07-19T20:57:20.023 回答