A teammate and I were discussing different ways to create user controls in WPF. Specifically, the discussion was in context to a numeric up/down user control built from scratch. It consists of a Label for a title, a TextBox for the value, a Label for the units and 2 buttons for the up/down action. The ultimate goal is to bind to the properties exposed by this user control from screen view models.
The TextBox xaml declaration for the user control is as follows:
<TextBox x:Name="Textbox" Text="{Binding TextboxValue, FallbackValue=0}" Width="100" Height="40" TextAlignment="Left" FontSize="28" VerticalAlignment="Center" BorderBrush="Black" BorderThickness="2"/>
The TextBoxes Text property is bound to the code-behind for the user controls view. Snippets of the relevant parts of the code-behind are shown below.
public static readonly DependencyProperty TextboxValueProperty = DependencyProperty.Register("TextboxValue",
typeof(double), typeof(IncrementDecrementTextbox), new PropertyMetadata(12.0d, new PropertyChangedCallback(OnTextboxValueChanged)));
public IncrementDecrementTextbox()
{
InitializeComponent();
this.DataContext = this;
}
public double TextboxValue
{
get
{
return (double)GetValue(TextboxValueProperty);
}
set
{
SetValue(TextboxValueProperty, value);
NotifyTextboxValueUpdated();
}
}
private static void OnTextboxValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
IncrementDecrementTextbox control = d as IncrementDecrementTextbox;
control.OnTextboxValueChanged(e);
}
private void OnTextboxValueChanged(DependencyPropertyChangedEventArgs e)
{
TextboxValue = Convert.ToDouble(e.NewValue);
}
public event EventHandler TextboxValueUpdated;
private void NotifyTextboxValueUpdated()
{
TextboxValueUpdated?.Invoke(this, EventArgs.Empty);
}
The implementation of this user control is confusing to me. I don't understand why data binding is being used between the view & it's code-behind part. I would think that since the code-behind and the corresonding xaml view are essentially one in the same, that one would want to access elements declared in xaml directly from the code behind by setting the x:Name property of the element. But, I might be missing something.
Is binding between the view & the code-behind a standard practice when creating user controls? If not, is there a better way to do it?
Thanks!