簡體   English   中英

WPF:以編程方式更改 MouseOver 的 ListBoxItem 背景屬性

[英]WPF: Change ListBoxItem Background property for MouseOver programmatically

我的應用程序使用 c# 代碼創建了一個ListBox 我已經設法設置了我的 ListBox [白色] 的背景。 並設法為ListBoxItem ( BackgroundProperty & MarginProperty ) 設置了一些樣式屬性。

對於MouseOver我定義了一個Trigger - 並設法設置BorderThicknessProperty & MarginProperty 看這篇文章

但無法更改IsMouseOver背景BackgroundProperty 我試圖這樣做:

triggerIsMouseOver.Setters.Add(new Setter(ListBoxItem.BackgroundProperty, Brushes.Purple)); // Does not work

在此處輸入圖片說明

我有這個簡單的 XAML:

<Grid Background="Black">
   <StackPanel x:Name="myStackPanel" Margin="10"></StackPanel>
</Grid>

我的代碼是這樣的:

List<string> ItemsList = new List<string>();

for (int i = 0; i < 5; i++)
{
    ItemsList.Add("ListBoxItem: " + i.ToString());
}

Trigger triggerIsMouseOver = new Trigger
{
    Property = ListBoxItem.IsMouseOverProperty,
    Value = true
};
            
triggerIsMouseOver.Setters.Add(new Setter(ListBoxItem.BorderThicknessProperty, new Thickness(2)));
triggerIsMouseOver.Setters.Add(new Setter(ListBoxItem.MarginProperty, new Thickness(1)));

// Does not work
triggerIsMouseOver.Setters.Add(new Setter(ListBoxItem.BackgroundProperty, Brushes.Purple)); 

Style styleListBoxItem = new Style
{
    TargetType = typeof(ListBoxItem),
};
styleListBoxItem.Triggers.Add(triggerIsMouseOver);
styleListBoxItem.Setters.Add(new Setter(ListBoxItem.BackgroundProperty, Brushes.Orange));
styleListBoxItem.Setters.Add(new Setter(ListBoxItem.MarginProperty, new Thickness(2)));

ListBox listBox = new ListBox
{
    ItemsSource = ItemsList,
    ItemContainerStyle = styleListBoxItem,
    Background = Brushes.White
};
            
myStackPanel.Children.Add(listBox);

樣式無效的原因是: ListboxItem的默認模板包含一個內置的 Ismouseover 觸發器,它改變了模板元素的效果。 導致您設置的 Ismouseover 無效。 因此,您需要像這樣定義一個控件模板。 如下:

<controltemplate targettype="listboxitem">
    <Border x:Name="Bd"
        BorderBrush="{TemplateBinding BorderBrush}" 
        BorderThickness="{TemplateBinding BorderThickness}" 
        Background="{TemplateBinding Background}" 
        Padding="{TemplateBinding Padding}" 
        SnapsToDevicePixels="true">
        <ContentPresenter 
            HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
            SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" 
            VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
    </Border>
</controltemplate>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM