Reputation: 75
In wpf mvvm mode, i have a usercontrol like this
<UserControl MyControl>
<Grid>
<DataGrid
ItemsSource="{Binding MySource}"
Visibility = "{Binding the usercontrol's datacontext.UserGrade}"
/>
</Grid>
</UserControl>
In my MainPageView I use it like this
<Window:MainPageView
xmlns:vm="clr-namespace:My.ViewModel"
xmlns:userCtl="clr-namespace:My.Controls"
<Window.DataContext>
<vm:MainPageViewModel/>
</Window.DataContext>
<userCtl:MyControl>
<userCtl:Mycontrol.DataContext>
<vm:MyControlViewModel/>
</userCtl:Mycontrol.DataContext>
<userCtl:MyControl>
</Window:MainPageView>
Now here's the question, how can I access the MyUserControl's datacontext.UserVisiable, and binding to the MyUserControl's datagrid visibility? I tried to use {RelativeSource FindAncestor, AncestorType={x:Type UserControl}} but it did not work, or I didi it wrong? Thanks!
Upvotes: 0
Views: 81
Reputation: 1165
You could try this:
<Grid>
<DataGrid ItemsSource="{Binding MySource}"
Visibility = "{Binding DataContext.UserGrade, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
</Grid>
Explanation: Using RelativeSource for the Binding Source, helps you navigate throw the visual tree, to the first ancestor of the current control, of the type specified (UserControl). It then uses the UserControl.DataContext.UserGrade as the binding property.
If the Usercontrol.DataContext is null, then the binding will not work. As specified in the question, userControl has a DataContext that contains that property.
Also, you could try setting the AncestorType=location:MyControl
, in case UserControl is not enough. (location: is the namespace where your control is located)
Upvotes: 0