下面的xaml不起作用,因为对于ListBoxItem,BacckGround表示TextBlock下的颜色。
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="{DynamicResource Theme.Button.Background.Hover}" />
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"
Background="{DynamicResource Theme.Button.Background}"
Foreground="{DynamicResource Theme.Button.Foreground}"
Padding="{DynamicResource Theme.Button.Padding}"/>
</DataTemplate>
</ListBox.ItemTemplate>
对于请求,我在这里添加我的实际代码(SelectButton可以在https://gist.github.com/loraderon/580405找到):
<cntrls:SelectButton x:Name="Insert_BtnStartPolyline" Grid.Row="3" ItemsSource="{Binding Path=InsertLineItemsSource}" Command="{ui:CommandHandler OpenVersion}" HorizontalAlignment="Left" MinWidth="100">
<cntrls:SelectButton.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
</Style>
</cntrls:SelectButton.ItemContainerStyle>
<cntrls:SelectButton.Resources>
<Style TargetType="TextBlock">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Chartreuse" />
</Trigger>
</Style.Triggers>
</Style>
</cntrls:SelectButton.Resources>
<cntrls:SelectButton.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"
Background="{DynamicResource Theme.Button.Background}"
Foreground="{DynamicResource Theme.Button.Foreground}"
Padding="{DynamicResource Theme.Button.Padding}"
HorizontalAlignment="Stretch"/>
</DataTemplate>
</cntrls:SelectButton.ItemTemplate>
</cntrls:SelectButton>
答案 0 :(得分:1)
看起来正确答案是这样的。我不明白为什么在cntrls中定义TextBlock样式:SelectButton.Resources无法工作,但无论如何我们都不需要它。
这里的关键是不在Background
的属性中设置默认TextBlock
,而是在Setter
的{{1}}中设置默认Style
。这是因为,根据设计,属性事物会覆盖样式所做的任何事情。这实际上是一件好事(一旦你知道它!)因为它允许你显式覆盖控件的特定实例上的样式。
<DataTemplate>
<TextBlock
Text="{Binding}"
Foreground="{DynamicResource Theme.Button.Foreground}"
Padding="{DynamicResource Theme.Button.Padding}"
HorizontalAlignment="Stretch"
>
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Background" Value="{DynamicResource Theme.Button.Background}" />
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Chartreuse" />
</Trigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</DataTemplate>