2017-09-14 45 views
-1

我想設置控件的背景顏色,只需按住鼠標左鍵,然後我希望此控件返回到其正常行爲(觸發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

請張貼代碼。否則,人們只是在猜測。 – w0051977

+0

難道你不能再爲'IsPressed'做另一個觸發器嗎? – sTrenat

+0

「ListBoxItem」沒有'IsPressed'屬性 – semidude

回答

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)); 

} 

code-behind:

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> 
相關問題