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?