Binding Nested User Controls to Composite View Model

data-binding, user-controls, wpf

Solution

The whole problem was that I was setting my DataContext at the UserControl level, which was "peeking out" into the parent control. Thanks to LPL for pointing me to the blog post which clarified the issue: A Simple Pattern for Creating Re-useable UserControls in WPF / Silverlight

It has nothing to do with RelativeSource vs. ElementName vs. setting the DataContext in the codebehind; these are all different ways of accomplishing the same thing. The problem is evident in the diagram near the bottom of that blog post. Doing this in the child control (SuperTextControl):

<UserControl x:Class="SuperTextControl" ... >
  <UserControl.DataContext>
    <Binding RelativeSource="{RelativeSource Self}"/>
  </UserControl.DataContext>
  ...
</UserControl>

Is equivalent to declaring the control in the parent like this:

<local:SuperTextControl Says="{Binding Path=SomeText}">
  <local:SuperTextControl.DataContext>
    <Binding RelativeSource="{RelativeSource Self}" />
  </local:SuperTextControl.DataContext>
</local:SuperTextControl>

It makes sense that this won't work. My previous answer is incorrect: changing to ElementName has the same problem if the DataContext is defined in the same way. To get around this, set up your "internal" DataContext on the outermost child of the UserControl, rather than the UserControl itself:

<UserControl x:Class="SuperTextControl" x:Name="SuperTextControl">
  <Grid>
    <Grid.DataContext>
      <Binding ElementName="SuperTextControl" />
    </Grid.DataContext>
    <TextBox Name="SaysInput" Text="{Binding Path=Says}" />
  </Grid>
</UserControl>

Problem

I have a very simple composite model made of two classes: ``` Public Class ParentModelVM Public Property Name As String Public Property ChildModel As ChildModelVM Public Sub New() Name = "A Parent Model" ChildModel = New ChildModelVM With {.Name = "A Child Model"} End Sub End Class Public Class ChildModelVM Public Property Name As String Public Property Description As String End Class ``` Both implement INotifyPropertyChanged, which I have abbreviated out. I am attempting to produce a User Control to edit a ParentModelVM: ``` <UserControl x:Class="EditParentModel" .../> <UserControl.DataContext> <Binding RelativeSource="{RelativeSource Self}" Path="ViewModel" /> </UserControl.DataContext> <TextBox Name="NameInput" Text="{Binding Path=Name}"/> <local:EditChildModel x:Name="ChildModelInput" ViewModel="{Binding Path=ChildModel}"/> </UserControl> ``` ViewModel is a ParentModelVM that is registered as a DependencyProperty that binds two-way by default. I have a similar UserControl called EditChildModel that has a ViewModel property of type ChildModelVM, also registered as a DependencyProperty that binds two-way by default. This logic seems to make sense to me: ParentModelVM has a String that is edited with a TextBox control whose Text property is bound, and it has a ChildModelVM that is edited with an EditChildModel control whose ViewModel property is bound. ParentModelVM.Name correctly binds to its text box, and the two ChildViewModelVM properties correctly bind to their text boxes. However, EditParentModel.ViewModel.ChildModel is not the same object as EditChildModel.ViewModel, and I cannot figure out why. The behavior of the entire application is exactly the same if I remove the `ViewModel="{Binding Path=ChildModel}"` attribute from the EditParentModel UserControl. For example, NameInput initalizes with "A Parent Model", but EditChildModel.NameInput does not initialize with "A Child Model" like I expect. Any help on this would be greatly appreciated. Thanks! --Edit-- Ok, I've simplified this beyond absurdity, and it still doesn't work. I have a model called SimpleParent. This is the entire code: ``` Imports System.ComponentModel Public Class SimpleParent Implements INotifyPropertyChanged Private _someText As String Public Property SomeText As String Get Return _someText End Get Set(ByVal value As String) _someText = value RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("SomeText")) End Set End Property Public Sub New() SomeText = "This is some text." End Sub Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged End Class ``` I created a UserControl called "SuperTextControl" that acts exactly like a TextBox, with a DependencyProperty called "Says" instead of Text. Here is the entire XAML: ``` <UserControl x:Class="SuperTextControl" 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" mc:Ignorable="d" d:DesignHeight="23" d:DesignWidth="300"> <UserControl.DataContext> <Binding RelativeSource="{RelativeSource Self}"/> </UserControl.DataContext> <TextBox Name="SaysInput" Text="{Binding Path=Says}" /> </UserControl> ``` And here is the codebehind: ``` Public Class SuperTextControl Public Shared ReadOnly SaysProperty As DependencyProperty = DependencyProperty.Register("Says", GetType(String), GetType(SuperTextControl)) Public Property Says As String Get Return CTypeDynamic(Of String)(GetValue(SaysProperty)) End Get Set(ByVal value As String) SetValue(SaysProperty, value) End Set End Property End Class ``` Then I created a SimpleParentControl, which has a SimpleParent DependencyProperty. I have it as a DP because I might want to nest this control inside of other controls which bind to the SimpleParent property. Here is the entire XAML: ``` <UserControl x:Class="SimpleParentControl" 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:WpfTest" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <UserControl.DataContext> <Binding RelativeSource="{RelativeSource Self}" Path="SimpleParent" /> </UserControl.DataContext> <StackPanel> <TextBox Text="{Binding Path=SomeText}" /> <local:SuperTextControl Says="{Binding Path=SomeText}" /> </StackPanel> </UserControl> ``` And the entire codebehind: ``` Public Class SimpleParentControl Public Shared ReadOnly SimpleParentProperty As DependencyProperty = DependencyProperty.Register("SimpleParent", GetType(SimpleParent), GetType(SimpleParentControl)) Public Property SimpleParent As SimpleParent Get Return CTypeDynamic(Of SimpleParent)(GetValue(SimpleParentProperty)) End Get Set(ByVal value As SimpleParent) SetValue(SimpleParentProperty, value) End Set End Property Public Sub New() ' This call is required by the designer. InitializeComponent() ' Add any initialization after the InitializeComponent() call. SimpleParent = New SimpleParent() End Sub End Class ``` The TextBox in SimpleParentControl displays "This is some text", as expected. The local:SuperTextControl displays nothing. This is the simplest example I can possibly think of of creating a reusable UserControl, and yet it doesn't work. Surely, someone has had some success creating a re-usable UserControl as simple as a custom textbox, but no online tutorials discuss specifically how to do this. This is an extremely trivial example that fails for seemingly no reason. I would very much appreciate any insight into this. Thanks.

Original source