wpf - WPF,按钮继承 Foreground 的内容
问题描述
问题:如何设计按钮,它继承Foreground
自其父级,但允许通过样式更改它?
更准确地说,给定以下按钮:
<StackPanel TextBlock.Foreground="Red">
<ToggleButton Width="16" Height="16" FontSize="10" Style="{StaticResource ...}">
<Grid>
<Path Width="8" Height="8" Fill="...">
<Path.Data>
<PathGeometry Figures="M 1 0 L 1 4 L 0 4 L 0 5 L 3 5 L 3 8 L 4 8 L 4 5 L 7 5 L 7 4 L 6 4 L 6 0 L 1 0 z M 2 1 L 4 1 L 4 4 L 2 4 L 2 1 z " FillRule="NonZero"/>
</Path.Data>
</Path>
</Grid>
</ToggleButton>
</StackPanel>
我需要它:
- Path 的填充颜色与 StackPanel 的当前前景颜色匹配,并且
- 当用户将鼠标悬停在按钮上时,路径的填充颜色变为某种特定的、恒定的颜色。
我尝试设计按钮的样式,包括ControlTemplate
,但Foreground
. Button 通过主题将其Foreground
属性设置为某些,因此它与'sDynamicResource
不匹配。StackPanel
Foreground
显然我可以绑定它,但随后样式和控制模板触发器停止工作,因为我已经为依赖属性设置了一个立即值,这推翻了所有其他为其提供值的方法。
为了给出问题的背景,这就是我想要实现的目标:
解决方案
您可以像这样绑定到父TextBlock.Foreground
级的附件:ToggleButton
Panel
<Path Width="8" Height="8"
Fill="{Binding (TextBlock.Foreground),
RelativeSource={RelativeSource AncestorType=Panel, AncestorLevel=2}}">
...
如果你想Fill
在鼠标悬停时改变,你可以Style
用 a 定义 a DataTrigger
:
<StackPanel TextBlock.Foreground="Red">
<ToggleButton Width="16" Height="16" FontSize="10">
<Grid>
<Path Width="8" Height="8">
<Path.Data>
<PathGeometry Figures="M 1 0 L 1 4 L 0 4 L 0 5 L 3 5 L 3 8 L 4 8 L 4 5 L 7 5 L 7 4 L 6 4 L 6 0 L 1 0 z M 2 1 L 4 1 L 4 4 L 2 4 L 2 1 z "
FillRule="NonZero"/>
</Path.Data>
<Path.Style>
<Style TargetType="Path">
<Setter Property="Fill" Value="{Binding (TextBlock.Foreground),
RelativeSource={RelativeSource AncestorType=Panel, AncestorLevel=2}}" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsMouseOver,
RelativeSource={RelativeSource AncestorType=ToggleButton}}" Value="True">
<Setter Property="Fill" Value="Blue" />
</DataTrigger>
</Style.Triggers>
</Style>
</Path.Style>
</Path>
</Grid>
</ToggleButton>
</StackPanel>
推荐阅读
- c# - EF-Core 5:IDbContextTransaction 没有“GetDbContextTransaction()”的定义。如何正确使用不同的上下文?
- node.js - 使用异步 axios 获取服务器错误响应
- debugging - Visual Studio 2019 没有调试我的所有代码
- python - 如何从消息(discord.py)中删除代码语法?
- python - 如何返回用户名而不是 ID
- java - spring-boot-starter-oauth2-resource-server vs spring-cloud-starter-oauth2 使用哪个?
- java - 如何在hibernate中找到类表映射?
- python - 在 tkinter 中调整图片大小
- postgresql - 升级 postgresql 版本时我应该使用气流升级b吗?
- jupyter - jupyter notebook "c.NotebookApp.certfile = " 错误