如何解决WPF:以编程方式更改MouseOver的ListBoxItem背景属性
我的应用使用c#代码创建了一个ListBox
。我已经成功设置了ListBox的背景[白色]。并设法为ListBoxItem
(BackgroundProperty
和MarginProperty
)设置了一些样式属性。
对于 MouseOver ,我定义了Trigger
-并成功设置了BorderThicknessProperty
和MarginProperty
。看到这个article
但是无法更改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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。