簡體   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