繁体   English   中英

ListBoxItem的样式不起作用

[英]Styling of ListBoxItem Not Working

我正在尝试设置列表框中的ListBoxItems的样式,但是ListBoxItem的内容没有显示,并且颜色的任何变化都不明显。 唯一起作用的是我应用于每个列表项底部的“边界底部”。

<Style x:Key="ListItemStyle" TargetType="{x:Type ListBoxItem}">
    <Setter Property="OverridesDefaultStyle" Value="True" />
    <Setter Property="MinHeight" Value="30" />
    <Setter Property="Foreground" Value="Black" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate>
                <Border BorderBrush="#FF66AFDE" BorderThickness="0 0 0 1" />
                <ControlTemplate.Triggers>
                    <Trigger Property="IsFocused" Value="True">
                        <Setter Property="Background" Value="Red"></Setter>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style> 

ListBoxItem控件模板中使用面板/容器/装饰器设置背景色。 (似乎设置选择背景颜色的逻辑会干扰控制其背景颜色的尝试。)

<ControlTemplate TargetType="{x:Type ListBoxItem}">
    <Border
        Name="PART_Border"
        Focusable="true"
        Background="{TemplateBinding Background}"
        BorderBrush="#FF66AFDE"
        BorderThickness="0 0 0 1"
    >
        <ContentPresenter />
    </Border>
    <ControlTemplate.Triggers>
        <Trigger Property="IsFocused" Value="True">
            <Setter
                Property="Background"
                Value="Red"
                TargetName="PART_Border"
            />
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

另请注意, Border.Focusable默认为false 如果将其设置为true不起作用(我承认,我尚未测试),请使用其他容器控件代替Border。

另外,如果您将显示的内容具有任何获得焦点的控件(例如按钮或文本字段),则触发器可能无法按预期方式工作,因为当内容的控件具有焦点时,边框可能没有焦点。 此外,在控件之间进行制表可能会表现出意外的行为。 如果您必须处理这种情况,请尝试在ItemTemplate中处理触发器。

关于ContentPresenter不显示任何内容:根据ItemsSource中元素的类型,您可能需要定义ListBox.ItemTemplate (或ListBox.ItemTemplateSelector ),否则ContentPresenter可能不知道显示什么。

尝试这个

 <Style x:Key="ListItemStyle" TargetType="{x:Type ListBoxItem}">
        <Setter Property="OverridesDefaultStyle" Value="True" />
        <Setter Property="MinHeight" Value="30" />
        <Setter Property="Foreground" Value="Black" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ListBoxItem}">
                    <Border BorderBrush="#FF66AFDE" BorderThickness="0 0 0 1" x:Name="border">
                        <ContentPresenter/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsFocused" Value="True">
                            <Setter TargetName="border" Property="Background" Value="Red"></Setter>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

我希望这个能帮上忙

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM