我想将控件的背景颜色设置为按下鼠标左键的时间,然后我希望此控件恢复其正常行为(MouseOver的触发器等)。但是当我在代码隐藏中覆盖属性时,触发器将停止工作。怎么解决?我尝试在MouseUp事件上将属性设置为null,但它无论如何都不起作用。
代码:
private void Item_OnMouseDown(object sender, MouseButtonEventArgs e)
{
var item = sender as ListBoxItem;
item.Background = Application.Current.Resources["BlueLightBrush"];
}
以这种方式设置Background
之后,它将保持不变,我下次将设置它(触发器不会进行任何更改)
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="{StaticResource BlueDarkBrush}"/>
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="{StaticResource BlueDarkBrush}"/>
<Setter Property="BorderBrush" Value="{StaticResource BlueDarkBrush}"/>
</Trigger>
</ControlTemplate.Triggers>
答案 0 :(得分:0)
我设法通过附属财产做我想要的事情:
public static class ListBoxItemAttachedProperties
{
public static bool GetIsMouseDown(DependencyObject obj)
{
return (bool)obj.GetValue(IsMouseDownProperty);
}
public static void SetIsMouseDown(DependencyObject obj, bool value)
{
obj.SetValue(IsMouseDownProperty, value);
}
public static readonly DependencyProperty IsMouseDownProperty =
DependencyProperty.RegisterAttached("IsMouseDown", typeof(bool), typeof(UIElementAttachedProperties), new PropertyMetadata(false));
}
代码隐藏:
private void Item_OnMouseDown(object sender, MouseButtonEventArgs e)
{
var listBoxItem = sender as ListBoxItem;
listBoxItem.SetValue(ListBoxItemAttachedProperties.IsMouseDownProperty, true);
}
private void Item_OnMouseUp(object sender, MouseButtonEventArgs e)
{
var listBoxItem = sender as ListBoxItem;
listBoxItem.SetValue(ListBoxItemAttachedProperties.IsMouseDownProperty, false);
}
XAML:
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="{StaticResource BlueDarkBrush}"/>
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="{StaticResource BlueDarkBrush}"/>
<Setter Property="BorderBrush" Value="{StaticResource BlueDarkBrush}"/>
</Trigger>
<Trigger Property="local:ListBoxItemAttachedProperties.IsMouseDown" Value="True">
<Setter Property="Background" Value="{StaticResource BlueLightBrush}"/>
</Trigger>
</ControlTemplate.Triggers>