提问者:小点点

访问userctrol的数据文本不适合我


在wpf mvvm模式下,我有一个这样的用户控件

<UserControl  MyControl>
  <Grid>
    <DataGrid
       ItemsSource="{Binding MySource}"         
       Visibility = "{Binding the usercontrol's datacontext.UserGrade}"
    />
  </Grid>
</UserControl>

在我的Main PageView中,我这样使用它

<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>

现在的问题是,我如何访问MyUserControl的数据文本。UserVisiable,并绑定到MyUserControl的数据网格可见性?我试图使用{RelativeSource FindAncestor, AncestorType={x: Type UserControl}}但它不起作用,还是我做错了?谢谢!


共1个答案

匿名用户

你可以试试这个:

        <Grid>
        <DataGrid ItemsSource="{Binding MySource}"    
                  Visibility = "{Binding DataContext.UserGrade, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
    </Grid>

说明:对绑定源使用RelativeSource可以帮助您导航并将可视化树抛出到指定类型(UserControl)的当前控件的第一个祖先。然后它使用UserControl。数据上下文。UserGrade作为绑定属性。

如果用户控件。DataContext为空,则绑定将无法工作。如问题中指定的,userControl有一个包含该属性的DataContext。

此外,您还可以尝试设置AncestorType=location:MyControl,以防UserControl不够用。(位置:控件所在的命名空间)