Search code examples
c#wpfmvvmdependency-properties

UserControl using WPF, MVVM and DP


I am designing a NumericUpDownControl UserControl and have successfully implemented it in my MainWindow.xaml as follows:

<UserControl x:Class="SettingsDialog.Controls.NumericUpDownControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:SettingsDialog.Controls"
             xmlns:viewModels="clr-namespace:SettingsDialog.ViewModels"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800"
             DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="18"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <TextBox Text="{Binding Value}" Grid.Row="0" Grid.RowSpan="2" Height="20" VerticalContentAlignment="Center"/>
        <RepeatButton Content="5" Grid.Column="1" Grid.Row="0" FontSize="8" Height="10" FontFamily="Marlett" VerticalContentAlignment="Center"/>
        <RepeatButton Content="6" Grid.Column="1" Grid.Row="1" FontSize="8" Height="10" FontFamily="Marlett"  VerticalContentAlignment="Center"/>
    </Grid>
</UserControl>

In the code-behind of my UserControl, I have defined the following:

  public static readonly DependencyProperty ValueProperty =
     DependencyProperty.Register(
        "Value", typeof(int),
        typeof(NumericUpDownControl)
     );

  public int Value
  {
     get => (int)GetValue(ValueProperty);
     set => SetValue(ValueProperty, value);
  }

It works fine as I can use it in my MainWindow.xaml like this:

<controls:NumericUpDownControl Width="100" Value="10"/>

However, when I attempt to set a ViewModel for my UserControl, the TextBox within the UserControl no longer recognizes the Value dependency property. How can I properly implement a ViewModel for my UserControl while still allowing for the ability to set the Value property from outside the control? Is there an issue with my current implementation that is causing this issue?


Solution

  • This should bind the Text property of the TextBox to the Value property of the UserControl regardless of its DataContext:

    <TextBox Text="{Binding Value, RelativeSource={RelativeSource AncestorType=UserControl}}" Grid.Row="0" Grid.RowSpan="2" Height="20" VerticalContentAlignment="Center"/>