Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding of TextBlock inside Custom Control to dependency property of the same Custom Control

I have a custom control with a TextBlock inside it:

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

And this Custom control has a dependency property:

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

}

I want the value of "CustNo" property be transfered in "Text" property of TextBlock in each instance of the Custom Control. But my:

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

isn't working.

Isn't working also with Path=CustNoProperty:

Text="{Binding Source=CustControl,Path=CustNoProperty}"
like image 262
rem Avatar asked Dec 06 '22 04:12

rem


1 Answers

You need a TemplateBinding, like

<TextBlock
   Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=CustNo}" />
like image 171
kiwipom Avatar answered Dec 11 '22 08:12

kiwipom