4

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

2 Answers 2

10

You need a TemplateBinding, like

<TextBlock
   Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=CustNo}" />
Sign up to request clarification or add additional context in comments.

1 Comment

ps there's an excellent (if a little dated) dnrtv show on creating custom controls at dnrtv.com/default.aspx?showNum=72
6

Try the answers to this SO question. I think you'll want the third example. ie:

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

2 Comments

Simeon, thank you. Your answer is all I need. I'm sorry that it's impossible to select several identical right answers, which were posted at the same time as both accepted.
Well mine answer was posted 2 minutes before Ian's, but you had to be there at the time to notice. No stress. Maybe next time...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.