在UserControl模板中,TemplateBinding是如何工作的?

8

我是一个新手,正在创建用户控件,现在我正在尝试自定义以下用户控件模板:

<UserControl x:Class="WpfApplication1.PieButton"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300" Loaded="OnLoaded">
    <UserControl.Template>
        <ControlTemplate>
            <Path Name="path" Stroke="Aqua" StrokeThickness="3">
                <Path.Fill>
                    <SolidColorBrush Color="{TemplateBinding Fill}" />
                </Path.Fill>
                <Path.Data>
                ......
</UserControl>

与此同时,我已经在后端代码中创建了DependencyProperty:

public partial class PieButton : UserControl
{
    public PieButton()
    {
        InitializeComponent();
    }

    private void OnLoaded(object sender, RoutedEventArgs e)
    {

    }



    public Color Fill
    {
        get { return (Color)GetValue(FillProperty); }
        set { SetValue(FillProperty, value); }
    }

    public static readonly DependencyProperty FillProperty =
        DependencyProperty.Register("Fill", typeof(Color), typeof(PieButton));
    ......

我希望在 XAML 中使用 TemplateBinding 将 PieButton 的 Fill 属性绑定到路径对象的填充。然而 Visual Studio 设计器警告我“Fill属性不可访问或无法识别”。

根据我的理解,TemplateBinding 会从应用此控件模板的元素中查找属性名称,这里应该是 PieControl,但为什么这里无法访问 Fill 属性呢?

顺便说一下:

我测试了以下绑定方式,可以成功运行:

Color="Binding Fill,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type UserControl}}"

但我仍然认为TemplateBinding应该能够在这种情况下工作,请指出我的错误。谢谢。
1个回答

21

1
非常感谢您。 - m4design

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接