wpf - 如何绑定(bind)到 ControlTemplate 内的元素?

标签 wpf data-binding controltemplate

我在 wpf 中创建了两个自定义控件:Control_AControl_B。它们都定义了一个ColorPropertyControl_AControlTemplateControl_B 实例组成,

<ControlTemplate 
   TargetType="{x:Type Control_A}">
   <Border 
      Background="{TemplateBinding Background}"
      BorderBrush="{TemplateBinding BorderBrush}"
      BorderThickness="{TemplateBinding BorderThickness}">

      <Control_B />

   </Border>
</ControlTemplate>

我想要的是将A.Color(目标)绑定(bind)到B.Color(源)。如何在 XAML 中实现这一点?

最佳答案

可以通过 TwoWay 绑定(bind)来完成。这种方式有它的缺点,但它有效,

<ControlTemplate 
   TargetType="{x:Type Control_A}">
   <Border 
      Background="{TemplateBinding Background}"
      BorderBrush="{TemplateBinding BorderBrush}"
      BorderThickness="{TemplateBinding BorderThickness}">

      <Control_B 
        Color="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Color, 
                Mode=TwoWay}"/>

   </Border>
</ControlTemplate>

关于wpf - 如何绑定(bind)到 ControlTemplate 内的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64116550/

相关文章:

.net - wpf listview拖动选择多个项目

wpf - 整合常见的 WPF 样式

c# - Asp.NET ListView数据控件动态Databind

wpf - DataContext 作为资源内转换器绑定(bind)的源

wpf - 如何在 WPF TreeView 中突出显示整行

c# - 访问 ControlTemplate 中的控件

c# - 基本 WPF 验证

c# - 在属性的父引用更改后刷新属性的绑定(bind)

c# - 同一 View WPF MVVM 中多个 ViewModel 的绑定(bind)

c# - 空字符串上的数据触发