我正在使用以下樣式:
<Style x:Key="ListBoxItemStyle" TargetType="{x:Type ListBoxItem}">
<Setter Property="Foreground" Value="{DynamicResource Button-Foreground}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<TextBlock Padding="10"
Background="{TemplateBinding Background}"
Foreground="{TemplateBinding Foreground}">
<ContentPresenter/>
</TextBlock>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Foreground" Value="{DynamicResource Button-Foreground-Disabled}"/>
</Trigger>
<Trigger Property="IsMouseCaptured" Value="True">
<Setter Property="Background" Value="{DynamicResource Button-Background-Hover}"/>
<Setter Property="Foreground" Value="{DynamicResource Button-Foreground}"/>
</Trigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsMouseOver" Value="True"/>
<Condition Property="IsMouseCaptured" Value="False"/>
</MultiTrigger.Conditions>
<Setter Property="Background" Value="{DynamicResource Button-Background-Hover}"/>
<Setter Property="Foreground" Value="{DynamicResource Button-Foreground-Hover}"/>
</MultiTrigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsSelected" Value="True"/>
<Condition Property="IsMouseOver" Value="False"/>
</MultiTrigger.Conditions>
<Setter Property="Background" Value="{DynamicResource Button-Foreground}"/>
<Setter Property="Foreground" Value="{DynamicResource Button-Foreground-Hover}"/>
</MultiTrigger>
</Style.Triggers>
</Style>
我遇到的問題是IsMouseCaptured觸發器永遠不會發生。IsMouseOver即使我單擊它,它也會保持樣式(背景故意使用相同的顏色,但我嘗試更改只是為了進行實驗,它根本沒有改變,前景當然也不會改變)。
有沒有辦法在單擊特定串列框項時觸發它?所有其他觸發器都按預期作業。
uj5u.com熱心網友回復:
有沒有辦法在單擊特定串列框項時觸發它?
不使用任何內置屬性。
您可以創建自己的自定義ListBoxItem,添加IsPressed可以系結到的屬性:
public class CustomListBoxItem : ListBoxItem
{
public static readonly DependencyProperty IsPressedProperty = DependencyProperty.Register(
nameof(IsPressed), typeof(bool), typeof(CustomListBoxItem), new PropertyMetadata(false));
public bool IsPressed
{
get => (bool)GetValue(IsPressedProperty);
set => SetValue(IsPressedProperty, value);
}
protected override void onm ouseDown(MouseButtonEventArgs e)
{
base.OnMouseDown(e);
IsPressed = true;
}
protected override void onm ouseUp(MouseButtonEventArgs e)
{
base.OnMouseUp(e);
IsPressed = false;
}
}
除非您ListBoxItem明確創建元素,否則您還需要一個自定義ListBox來生成您的自定義型別的容器:
public class CustomListBox : ListBox
{
protected override DependencyObject GetContainerForItemOverride() =>
new CustomListBoxItem();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/382133.html
