Selected item loses style when focus moved out in WPF ListBox

前端 未结 2 751
你的背包
你的背包 2020-12-14 16:35

What do I have?

I have a ListBox populated with items from an XML file. Given a DynamicResource for Style pro

相关标签:
2条回答
  • 2020-12-14 17:35

    The answer referenced will in some cases solve the problem, but is not ideal as it breaks when the control is disabled/readonly and it also overrides the color schemes, rather than taking advantage of them. My suggestion is to add the following in the ListBox tags:

    <ListBox....>
        <ListBox.Resources>
                <Style TargetType="ListBoxItem">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="ListBoxItem">
                                <Border Name="Border" Padding="2" SnapsToDevicePixels="true">
                                    <ContentPresenter />
                                </Border>
                                <ControlTemplate.Triggers>
                                    <Trigger Property="IsSelected" Value="true">
                                        <Setter TargetName="Border" Property="Background"
                                                Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                                    </Trigger>
                                </ControlTemplate.Triggers>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
            </Style>
        </ListBox.Resources>
    </ListBox>
    

    What this will do is set the Highlight background color on the list box item whenever it is selected (regardless of the control state).

    My answer is based on help from the answers already given to these answers, along with the following blog: http://blogs.vbcity.com/xtab/archive/2009/06/29/9344.aspx

    0 讨论(0)
  • 2020-12-14 17:40

    If you're only setting the background color, try replacing ControlBrush for the ListBox, as per this answer.

    0 讨论(0)
提交回复
热议问题