1

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?

1 Answer 1

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); }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I just found another answer similar to yours here: stackoverflow.com/questions/25989018/…
But for me it's not working this way. I miss something somewhere.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.