wpf - WPF - 如何从父元素中获取值?
问题描述
嗨,我正在尝试从 Button Content 传递到 ControlTemplate -> Label Content 我该怎么做?
我刚开始学习 xaml 并遇到这样的问题,我将非常感谢任何帮助。
代码:
<Style x:Key="CloseBtn" TargetType="Button">
<Setter Property="Content" Value="Flex"/> <!---From here --->
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Label Name="Border" Focusable="False" Background="#00ff0000" Foreground="#A770FA"
Content="" <--- Over here --->
VerticalContentAlignment="Center" HorizontalContentAlignment="Center"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>```
解决方案
在绑定中使用相对源绑定到父控件上的属性,在这种情况下,它可以是:
<Label Name="Border" Focusable="False" Background="#00ff0000" Foreground="#A770FA"
Content="{Binding RelativeSource={RelativeSource AncestorType={x:Type Button}},Path=Content}"
VerticalContentAlignment="Center" HorizontalContentAlignment="Center"/>
OR
<Label Name="Border" Focusable="False" Background="#00ff0000" Foreground="#A770FA"
Content="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Content}"
VerticalContentAlignment="Center" HorizontalContentAlignment="Center"/>
相对源还允许您绑定到同一控件上的属性、祖先到某个级别等。请参阅文档:https://docs.microsoft.com/en-us/dotnet/api/system.windows。 data.relativesource?view=net-5.0
推荐阅读
- python - 如何绘制基于区域的颜色编码python
- python - 如何将 postgres 日期时间列更改为默认为 datetime.utcnow
- python - 设置图像在主窗口中的位置,QPixmap
- sass - SCSS 检查 CSS 自定义 var 属性
- reactjs - 在标题属性中连接 React 中的多重道具
- javascript - 如何在不重新创建 React 中的整个列表的情况下更新项目
- node.js - 如何使用 https.request 执行获取请求?
- typescript - 如何合并两个接口类型与合并的重叠属性类型?
- java - Java switch case 中断方法
- javascript - 在 Eclipse JEE 中启用 javascript 内容辅助