我确信之前已经解决了这个问题,但我找不到合适的解决方案。我可能不知道我正在寻找的条款。
假设我有这个自定义控制模板
<Style x:Key="ColorPicker" TargetType="{x:Type local:ColorPicker}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:ColorPicker}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Thumb Width="30" Height="30" Canvas.Left="0" Canvas.Top="0">
<Thumb.Style>
<Style TargetType="Thumb">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Ellipse Fill="{TemplateBinding SelectedColor}" Width="30" Height="30" Stroke="Black" StrokeThickness="1" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Thumb.Style>
</Thumb>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
其中SelectedColor
是ColorPicker的属性。
在上面的示例中,模板绑定将在类型SelectedColor
的模板父级中查找Thumb
,但是如何才能获得与第二级模板父级的绑定?
答案 0 :(得分:5)
Fill="{Path=SelectedColor, RelativeSource={RelativeSource FindAncestor, AncestorType={local:ColorPicker}}}"
在ColorPicker样式中,这将遍历ColorPickers属性,而不是Thumb上的属性。我通常认为这是一个更安全的绑定,几乎不使用TemplateBinding。使用TemplateBinding在customcontrols中烧了这么多次!
无论如何完整代码:)
<Style x:Key="ColorPicker" TargetType="{x:Type local:ColorPicker}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:ColorPicker}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Thumb Width="30" Height="30" Canvas.Left="0" Canvas.Top="0">
<Thumb.Style>
<Style TargetType="Thumb">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Ellipse Fill="{Path=SelectedColor.Color, RelativeSource={RelativeSource FindAncestor, AncestorType={local:ColorPicker}}}" Width="30" Height="30" Stroke="Black" StrokeThickness="1" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Thumb.Style>
</Thumb>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
WPF Cheatsheet is a compact list of all types of bindings, very handy!
干杯,
了Stian