0

I am trying to create in WPF a user control that is a simple view, without view model. I have a label and a textBox inside.

ControlTextBox.xaml :

 <Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Name="LabelColumn"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Label Grid.Column="0" Name="LabelControl"></Label>
    <TextBox Grid.Column="1"
             Name="TextBox"
             Width="Auto"
             HorizontalAlignment="Stretch"
             Height="22"></TextBox>
</Grid>

ControlTextBox.xaml.cs :

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

    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string), typeof(ControlTextBox),
            new PropertyMetadata(default(string), new PropertyChangedCallback(OnTextChanged)));
    
    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

     private static void OnTextChanged(DependencyObject sender,
       DependencyPropertyChangedEventArgs args)
    {
        ControlTextBox controlTextBox = sender as ControlTextBox;
        controlTextBox.UpdateText(args);
    }
 
    private void UpdateText(DependencyPropertyChangedEventArgs args)
    {
        TextBox.Text = (string)args.NewValue;
    }
}

Where the control is used :

<controls:ControlTextBox Text="{Binding PersonModel.Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"/>

But this way, where I am using the control the binding is done in a single way. If the property from binding is changed I can see it in the textBox. But if I write something new in the textBox, the property from binding is not changed.

What should I do to make also the change from textBox to the binding property?

Lung Radu
  • 15
  • 3

1 Answers1

2

Use a RelativeSource Binding in ControlTextBox.xaml:

<TextBox ...
    Text="{Binding Text, RelativeSource={RelativeSource AncestorType=UserControl}}" />

and drop the PropertyChangedCallback:

public static readonly DependencyProperty TextProperty =
    DependencyProperty.Register(nameof(Text), typeof(string), typeof(ControlTextBox));

public string Text
{
    get { return (string)GetValue(TextProperty); }
    set { SetValue(TextProperty, value); }
}
Clemens
  • 123,504
  • 12
  • 155
  • 268
  • I just found another answer similar to yours here: https://stackoverflow.com/questions/25989018/wpf-usercontrol-twoway-binding-dependency-property – Lung Radu Oct 24 '20 at 17:50
  • But for me it's not working this way. I miss something somewhere. – Lung Radu Oct 24 '20 at 17:50