Search code examples
wpfbindingtextboxdependency-properties

WPF Simple TextBox Binding - Dependency Property Never Touched


I have a TextBox and I'm trying to bind it to a DependencyProperty. The property is never touched on load or when I type in the TextBox. What am I missing?

XAML

<UserControl:Class="TestBinding.UsernameBox"
        // removed xmlns stuff here for clarity>
    <Grid>
        <TextBox Height="23" Name="usernameTextBox" Text="{Binding Path=Username, ElementName=myWindow, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />
    </Grid>
</UserControl>

C#

public partial class UsernameBox : UserControl
{
    public UsernameBox()
    {
        InitializeComponent();
    }

    public string Username
    {
        get
        {
            // Control never reaches here
            return (string)GetValue(UsernameProperty);
        }
        set
        {
            // Control never reaches here
            SetValue(UsernameProperty, value);
        }
    }

    public static readonly DependencyProperty UsernameProperty
        = DependencyProperty.Register("Username", typeof(string), typeof(MainWindow));
}

Edit: I need to implement a DependencyProperty because I am creating my own control.


Solution

  • You never reach setter because it is CLR wrapper of dependency property, it is declared to be set from external sources, like mainWindow.Username = "myuserName";. When the property is set through binding and you want to see if it changed or not just add the PropertyMetadata to your declaration with PropertyChangedCallback, for example:

    public static readonly DependencyProperty UsernameProperty =
                DependencyProperty.Register("Username", typeof(string), typeof(MainWindow), new UIPropertyMetadata(string.Empty, UsernamePropertyChangedCallback));
    
            private static void UsernamePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
            {
                Debug.Print("OldValue: {0}", e.OldValue);
                Debug.Print("NewValue: {0}", e.NewValue);
            }
    

    With this code you will see changes of your property in Output Window of VS.

    For more info on callbacks please read Dependency Property Callbacks and Validation

    Hope this helps.