0

I'm trying to create a custom usercontrol in WPF, that includes a textbox and some other controls. I want to be able to bind a string property from the datacontext to my usercontrol, that is then passed on to the TextBox within my usercontrol.

If it was a regular textbox, I would do this to bind the property FirstName of the object in the DataContext:

<TextBox Text="{Binding FirstName}" />

In my CustomTextBox, I would like to be able to do this:

<local:CustomTextBox CustomText="{Binding FirstName}"/>

But I can't quite get the databinding to work.

Codebehind for my CustomTextBox:

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

    public static readonly DependencyProperty CustomTextProperty =
                DependencyProperty.Register(
                        "CustomText",
                        typeof(string),
                        typeof(CustomTextBox));

    public string CustomText
    {
        get
        {
            return (string)GetValue(CustomTextProperty);
        }
        set
        {
            SetValue(CustomTextProperty, value);
        }
    }
}

Xaml markup for CustomTextBox:

<Grid>
    <TextBox x:Name="tb" Text="{Binding CustomText}"></TextBox> 
</Grid>

What am I missing?

Lars Kristensen
  • 1,410
  • 19
  • 29
  • I got it working, thanks to the duped question - I guess you had to know that it is called TwoWay binding, in order to be able to search for a solution. – Lars Kristensen Jan 19 '21 at 13:58
  • 1
    Note that you can register the CustomText property with `FrameworkPropertyMetadataOptions.BindsTwoWayByDefault`. – Clemens Jan 19 '21 at 21:17
  • @Clemens, Thanks. Do I add it in the same `DependencyProperty` that I already have for the `Text` property? `public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(CustomTextBox), null);` – Lars Kristensen Jan 20 '21 at 09:12
  • 1
    See here: https://stackoverflow.com/a/42397657/1136211 – Clemens Jan 20 '21 at 11:16

0 Answers0