将边框颜色绑定到ListBox IsFocused属性

时间:2017-05-04 16:14:07

标签: wpf xaml

如何根据以下代码中的ListBox是否具有焦点来更改边框的颜色:

<LisBox ItemsSource="{Binding MyCollection}" x:Name="list"/>

<Border>
    <ContentControl Content="{Binding SelectedItem.Content, ElementName=list}"/>
</Border>

1 个答案:

答案 0 :(得分:1)

您可以DataTrigger的{​​{1}}风格使用Border;并将其绑定到ListBox的属性(在这种情况下,我使用IsKeyboardFocusWithin)。当ListBox失去焦点时,它将恢复原始颜色。

    <ListBox ItemsSource="{StaticResource MyCollection}" x:Name="list"/>
    <Border BorderThickness="2">
        <Border.Style>
            <Style TargetType="Border">
                <Setter Property="BorderBrush">
                    <Setter.Value>
                        <SolidColorBrush Color="Aquamarine" />
                    </Setter.Value>
                </Setter>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsKeyboardFocusWithin, ElementName=list}" Value="True">
                        <Setter Property="BorderBrush">
                            <Setter.Value>
                                <SolidColorBrush Color="Red" />
                            </Setter.Value>
                        </Setter>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Border.Style>
        <ContentControl Content="{Binding SelectedItem, ElementName=list}"/>
    </Border>