[英]Wpf listbox itemstlye triggers not working
我正在使用列表框itemstyle和觸發器來更改鼠標懸停顏色,但是該樣式似乎不起作用:
<ListBox ItemsSource="{Binding LocationItems}" SelectionChanged="RadListBox_SelectionChanged" Name="RLBLocations">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="BorderBrush" Value="#FF709A70"/>
<Setter Property="Height" Value="50"/>
<Setter Property="Width" Value="200"/>
<Setter Property="Foreground" Value="#FF5C5C5C"/>
<Setter Property="FontFamily" Value="Franklin Gothic Book"/>
<Setter Property="FontSize" Value="16"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<StackPanel Orientation="Horizontal" Height="50">
<Image Source="{Binding Icon}" Margin="0" Stretch="UniformToFill" Width="32" Height="32"/>
<TextBlock Margin="10,10,0,0" Text="{Binding Text.Text}" Foreground="Black" TextAlignment="Left"/>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="ToolTip" Value="{Binding ToolTip}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Background" Value="#FFF0F0F0"/>
<Style.Triggers>
<DataTrigger Binding="{Binding
RelativeSource={RelativeSource
Mode=FindAncestor,
AncestorType={x:Type ListBoxItem}},
Path=IsMouseOver}" Value="True">
<Setter Property="Background" Value="#FF709A70"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
我在輸出窗口中收到此錯誤:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ListBoxItem', AncestorLevel='1''. BindingExpression:Path=IsMouseOver; DataItem=null; target element is 'ListBoxItem' (Name=''); target property is 'NoTarget' (type 'Object')
我知道該錯誤,但需要幫助找出樣式-我嘗試使用datatemplate進行處理,但也沒有解決。
您的DataTrigger:
<DataTrigger Binding="{Binding RelativeSource={RelativeSource
Mode=FindAncestor,
AncestorType={x:Type ListBoxItem}},
Path=IsMouseOver}"
Value="True">
<!-- ... -->
</DataTrigger>
試圖找到(類的祖先ListBoxItem
)中的ListBoxItem
。 當然,除非將ListBoxItems
彼此嵌套在一起,否則這是不存在的。
更改為此:
<Trigger Property="IsMouseOver" Value="True">
<!-- ... -->
</Trigger>
此外,您將覆蓋ListBoxItem
的模板,並且在自定義模板中沒有指向ListBoxItem.Background
屬性的內容,該筆刷將永遠在屏幕上不可見。
我建議您將其用於StackPanel的背景:
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<StackPanel Orientation="Horizontal" Height="50" Background="{TemplateBinding Background}">
<!-- ... -->
</StackPanel>
</ControlTemplate>
另外,我認為您可能會將ListBoxItem.Template
的概念與ListBox.ItemTemplate
混淆,后者是用於在常規ListBoxItems中呈現Data
的DataTemplate
。 我建議您看一下本教程以獲取更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.