【问题标题】:How to bind to an element inside a ControlTemplate?如何绑定到 ControlTemplate 中的元素?
【发布时间】:2020-09-29 09:18:51
【问题描述】:

我在 wpf 中创建了两个自定义控件,Control_AControl_B。他们都定义了一个ColorPropertyControl_AControlTemplate 包含一个Control_B 实例,

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

      <Control_B />

   </Border>
</ControlTemplate>

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

【问题讨论】:

  • 我认为你把数据流弄混了。应该是ViewModel &gt; View &gt; Control_A &gt; ControlTemplate &gt; Control BControl_B 是模板组合的一部分,因此如果不通过Control_A 传递数据,您将无法直接绑定到它/动态提供数据。
  • 可能你是对的@Funk,但我不使用 MVVM。

标签: wpf data-binding controltemplate


【解决方案1】:

可以通过TwoWay 绑定来完成。这种方式有它的缺点,但它的工作原理,

<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>

【讨论】:

    【解决方案2】:

    我会尝试给 Control_B 一个名称并绑定到它的颜色。

    Color="{Binding ElementName=Foo, Path=Color}"
    

    【讨论】:

    • 但是你会在 Control_A 的 ControlTemplate 里面写这个吗?
    • 您想在自定义控件中使用颜色做什么由您决定。也许将其用作边框的背景,或者您可能需要更多可以分配它的元素。还是您只想将其分配给您的“自我”?
    • 我想要Control_B.Color 的值到Control_A.Color。但是两者的关系是一个是模板化的父级,另一个是模板化的子级。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 2018-11-08
    • 1970-01-01
    相关资源
    最近更新 更多