0
votes

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!

1
You want to access property of Window, but using UserControl type in FindAncestor... why?Sinatr
it's all ok because my viewmodel has the same property in the baseviewmodelCagaya Coper
You want to access MyUserControl's datacontext.Visibility. Do you have Visibility property on MyControlViewModel?Liero
yes i have a visibility propertyCagaya Coper
FindAncestor sucks. Just give the root a distinct name (a guid is even fine) and use ElementName=whatevs.user1228

1 Answers

0
votes

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)