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

时间:2009-12-06 10:07:00

标签: c# wpf data-binding 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>

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

    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); }
    }

}

我希望在Custom Control的每个实例中,TextBlock的“Text”属性中传递“CustNo”属性的值。 但我的:

Text="{Binding Source=CustControl,Path=CustNo}"

无效。

还没有使用Path = CustNoProperty:

Text="{Binding Source=CustControl,Path=CustNoProperty}"

2 个答案:

答案 0 :(得分:10)

你需要一个TemplateBinding,比如

<TextBlock
   Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=CustNo}" />

答案 1 :(得分:6)

尝试此SO question的答案。我想你会想要第三个例子。即:

{Binding Path=CustNo, RelativeSource={RelativeSource TemplatedParent}}