Data Binding is not working on a Customcontrol

Asked

Viewed 59 times

1

I’m trying to make a custom control that inherits from Textbox look like this:

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

    public static readonly DependencyProperty HeaderProperty =
            DependencyProperty.Register
            (
                nameof(Header),
                typeof(string),
                typeof(FieldControl),
                new PropertyMetadata(string.Empty)
            );

    public string Header
    {
        get { return (string)GetValue(HeaderProperty); }
        set { SetValue(HeaderProperty, value); }
    }
}

And in a dictionary of resources I have this:

<Style TargetType="{x:Type controls:FieldControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type controls:FieldControl}">
                <StackPanel>
                    <TextBlock Margin="2" Text="{TemplateBinding Header}" />
                    <TextBox Text="{TemplateBinding Text}" />
                </StackPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

The problem is that when performing a data connection to the Text property, I do not receive notifications for Inotifypropertychanged in the view model.

<controls:FieldControl Header="Nome:" Text="{Binding Nome, UpdateSourceTrigger=PropertyChanged}" />

What I’m doing wrong?

My Viewmodel implements Inotifypropertychanged and if I use a common Textbox I get the notifications correctly, which confirms that the problem is related to my control.

  • I’m pretty outdated in C#, but is that not the problem of this readonly? Since you try to assign the property by Set, you would not have to pass on to the textbox "ancestor"?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.