TemplateBinding not working for textbox text

5.3k views Asked by At

I have a custom control called EnhancedTextBox which is a UserControl that has a TextBox and a Button. To the consumer I want it to mostly look like a TextBox, so I did the following:

<UserControl.Template>
    <ControlTemplate TargetType="textBoxes:EnhancedTextBox">
    ...
    <TextBox Text="{TemplateBinding Text}"...

And in EnhancedTextBox I have

public static readonly DependencyProperty TextProperty =
  DependencyProperty.Register("Text", typeof (String), typeof (EnhancedTextBox));

public String Text
{
  get { return (String) GetValue(TextProperty); }
  set { SetValue(TextProperty, value); }
}

Yet, when I use it as the following:

<EnhancedTextBox Text="{Binding MyText, Mode=TwoWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}}" />

Then, MyText is never updated, as well as I inspect EnhancedTextBox.Text and it is null. What am I missing? I have been staring at this for a bit and can't figure out what is wrong. I even thought it might be the fact that I was using the same name, so create a property called Text1 which did not work....

Also of note, if I use a regular TextBox, then this all works. So, I am fairly certain the problem is with the EnhancedTextBox itself

2

There are 2 answers

3
Justin Pihony On BEST ANSWER

I figured it out after reading this MSDN about TemplateBinding. Specifically,

A TemplateBinding is an optimized form of a Binding for template scenarios, analogous to a Binding constructed with {Binding RelativeSource={RelativeSource TemplatedParent}}.

So, I decided to do this explicitly...which would allow me to set the UpdateSourceTrigger (still not sure why it doesn't default to PropertyChanged)

<TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Text, UpdateSourceTrigger=PropertyChanged}"....

And, now it is working. TemplateBinding does not even expose these properties....again, not sure why

1
user2880486 On

You are missing the CallBack when you register the property.

Here's a sample code.

    public bool IsSelected
    {
        get { return (bool)GetValue(IsSelectedProperty); }
        set { SetValue(IsSelectedProperty, value); }
    }

    public void IsSelectedChangedCallback()
    {

        //actions when property changed

    }

    private static void OnSelectedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        userControl.IsSelectedChangedCallback();
    }

    public static readonly DependencyProperty IsSelectedProperty = DependencyProperty.Register("IsSelected", typeof(bool), typeof(MyUserControl), new PropertyMetadata(new PropertyChangedCallback(OnSelectedChanged)));