将Custom Control内的TextBlock绑定到同一个Custom Control的依赖项属性

rem*_*rem 4 c# data-binding wpf xaml custom-controls

我有一个带有TextBlock的自定义控件:

<Style TargetType="{x:Type local:CustControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:CustControl}">
                <Border Background="Blue"
                        Height="26" 
                        Width="26" Margin="1">

                        <TextBlock x:Name="PART_CustNo"
                                   FontSize="10"
                                   Text="{Binding Source=CustControl,Path=CustNo}" 
                                   Background="PaleGreen" 
                                   Height="24" 
                                   Width="24"
                                   Foreground="Black">
                        </TextBlock>

                </Border>
             </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
Run Code Online (Sandbox Code Playgroud)

此自定义控件具有依赖项属性:

    public class CustControl : Control
{
    static CustControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(CustControl), new   FrameworkPropertyMetadata(typeof(CustControl)));
    }

    public readonly static DependencyProperty CustNoProperty = DependencyProperty.Register("CustNo", typeof(string), typeof(CustControl), new PropertyMetadata(""));

    public string CustNo
    {
        get { return (string)GetValue(CustNoProperty); }
        set { SetValue(CustNoProperty, value); }
    }

}
Run Code Online (Sandbox Code Playgroud)

我希望在自定义控件的每个实例中,TextBlock的"Text"属性中传递"CustNo"属性的值.但我的:

Text="{Binding Source=CustControl,Path=CustNo}"
Run Code Online (Sandbox Code Playgroud)

不工作.

不适用于Path = CustNoProperty:

Text="{Binding Source=CustControl,Path=CustNoProperty}"
Run Code Online (Sandbox Code Playgroud)

kiw*_*pom 10

你需要一个TemplateBinding,比如

<TextBlock
   Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=CustNo}" />
Run Code Online (Sandbox Code Playgroud)


Sim*_*rim 6

尝试这个问题的答案.我想你会想要第三个例子.即:

{Binding Path=CustNo, RelativeSource={RelativeSource TemplatedParent}}
Run Code Online (Sandbox Code Playgroud)