user7134019
user7134019

Reputation: 217

Binding UserControl property to parent data context

I've got a UserControl in a WPF MVVM application whose visibility I want to bind to a property in its parent's DataContext. The problem is that the child UC has it's own DataContext. So how do I use the child DataContext for the internals of the child UC and still use the parent DataContext for the visibility?

So for example, the DataContext of the parent control looks something like this

class Parent
{
    public Child Child { get; private set; }

    public Visibility ChildVisible
    {
        get { return Visibility.Visible; }
    }
}

In the XAML, how can I configure the Visibility binding so that it points to Parent.ControlVisible, instead of Child.ControlVisible?

<local:Child DataContext="{Binding Control}" Visibility="{Binding ControlVisible}" />

Upvotes: 2

Views: 5459

Answers (2)

Gijs Smit
Gijs Smit

Reputation: 36

You can refer to the parent user control by using ElementName, and use its DataContext, e.g.

<Border x:Name="parentControl" DataContext="{Binding Parent}" Visibility="Visible">

    <Border DataContext="{Binding Child}" Visibility="{Binding DataContext.MyVisibleProperty, ElementName=parentControl}">

    </Border>

</Border>

Upvotes: 2

rmojab63
rmojab63

Reputation: 3631

how do I use the child DataContext for the internals of the child UC

You should not set the DataContext of a UserControl (see this). Therefore, use RelativeResource or ElementName in the Bindings in your child UserControl. Note that You can use the DataContext of the parent in your child UserControl.

Also, don't forget to implement INotifyPropertyChanged for the models and/or view models.

Upvotes: 2

Related Questions