Reputation: 217
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
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
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