WPF:以编程方式更改MouseOver的ListBoxItem背景属性

问题描述

我的应用使用c#代码创建了一个ListBox。我已经成功设置了ListBox的背景[白色]。并设法为ListBoxItemBackgroundPropertyMarginProperty)设置了一些样式属性。

对于 MouseOver ,我定义了Trigger-并成功设置了BorderThicknessPropertyMarginProperty。看到这个article

但是无法更改IsMouseOver背景BackgroundProperty。我试图这样做:

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

enter image description here

我有这个简单的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>

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...