Search code examples
c#wpfxamluser-controlswpf-controls

WPF UserControl Dependency Property not working


In a WPF project (code below) I have a UserControl of type MyUserControl with a dependency property, called MyOrientation of type Orientation.

On the MainWindow I have 2 instances of MyUserControl, where via XAML I set the Orientation property on one to be Horizontal and the other instance to be Vertical.

I have made the MyOrientation property a DP as I want the ability to set it directly in XAML as in this example or using a binding.

My problem is that when I run the project both instances of the UserControl show up with the Orientation = Horizontal?

Could someone please tell me what I am doing wrong and how to fix it?

Many thanks in advance.

Here is the code:

MYUSERCONTROLVIEWMODEL:

public class MyUserControlViewModel : ViewModelBase
{
    private Orientation _myOrientation;
    public Orientation MyOrientation
    {
        get { return _myOrientation; }
        set
        {
            if (_myOrientation == value)
                return;
            _myOrientation = value;
            OnPropertyChanged();
        }
    }

}

MYUSERCONTROL.XAML

<UserControl x:Class="TestUserControlDPProblem.MyUserControl"
         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:TestUserControlDPProblem"
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<Grid x:Name="root">

    <Grid.DataContext>
        <local:MyUserControlViewModel/>
    </Grid.DataContext>

    <StackPanel Orientation="{Binding MyOrientation}">
        <TextBlock>Hello</TextBlock>
        <TextBlock>There</TextBlock>
    </StackPanel>
</Grid>

MYUSERCONTROL CODE BEHIND:

public partial class MyUserControl : UserControl
{
    MyUserControlViewModel _vm;

    public MyUserControl()
    {
        InitializeComponent();

        _vm = root.DataContext as MyUserControlViewModel;
    }

    public static readonly DependencyProperty MyOrientationProperty = DependencyProperty.Register("MyOrientation", typeof(Orientation), typeof(MyUserControl), new FrameworkPropertyMetadata(Orientation.Vertical, new PropertyChangedCallback(OnMyOrientationChanged)));

    private static void OnMyOrientationChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
    {
        var myUserControl = o as MyUserControl;
        myUserControl?.OnMyOrientationChanged((Orientation)e.OldValue, (Orientation)e.NewValue);
    }

    protected virtual void OnMyOrientationChanged(Orientation oldValue, Orientation newValue)
    {
        _vm.MyOrientation = newValue;
    }
    public Orientation MyOrientation
    {
        get
        {
            return (Orientation)GetValue(MyOrientationProperty);
        }
        set
        {
            SetValue(MyOrientationProperty, value);
        }
    }

}

MAINWINDOW.XAML

<Window x:Class="TestUserControlDPProblem.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:TestUserControlDPProblem"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <StackPanel>
        <local:MyUserControl Margin="10" MyOrientation="Horizontal"/>
        <local:MyUserControl Margin="10" MyOrientation="Vertical"/>
    </StackPanel>


</Grid>


Solution

  • The "internal" view model of the UserControl makes no sense and should not be there. You should instead bind directly to the dependency property by means of a RelativeSource or ElementName Binding:

    <StackPanel Orientation="{Binding MyOrientation,
                              RelativeSource={RelativeSource AncestorType=UserControl}}">
    

    You wouldn't even need the PropertyChangedCallback:

    public partial class MyUserControl : UserControl
    {
        public MyUserControl()
        {
            InitializeComponent();
        }
    
        public static readonly DependencyProperty MyOrientationProperty =
            DependencyProperty.Register(
                nameof(MyOrientation), typeof(Orientation), typeof(MyUserControl), 
                new FrameworkPropertyMetadata(Orientation.Vertical));
    
        public Orientation MyOrientation
        {
            get { return (Orientation)GetValue(MyOrientationProperty); }
            set { SetValue(MyOrientationProperty, value); }
        }
    }