从 DataTemplate(即用户控件)访问父 DataContext

Access parent DataContext from DataTemplate (which is User Control)

我有一个用户控件作为页面中的数据模板。 WP8 - access datacontext of parent 中有类似问题的响应,但定义了 DataTemplate "inside" ItemsControl。它在这样的场景中不起作用:

<Grid Name="layoutRootGrid">
        <ListView Name="listViewParent" HorizontalAlignment="Left" Height="458" Margin="42,24,0,0" VerticalAlignment="Top" Width="298" 
                  ItemsSource="{Binding ListViewSource}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <controls:ListViewControl />
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>

虽然 "ListViewControl" 是(ListViewSource 和 ParentProp 是集合,属性 来自绑定的 ViewModel - DataContext 的 listViewParent):

<Grid Background="Black" Name="templateGrid">
            <TextBlock Text="{Binding DataContext.ParentProp, ElementName=listViewParent, FallbackValue='couldnt get parent prop'}" VerticalAlignment="Top"/>
    </Grid>

您应该能够像这样绑定到父数据上下文:

<Grid Background="Black" Name="templateGrid">
    <TextBlock Text="{Binding DataContext.ParentProp, RelativeSource={RelativeSource AncestorType={x:Type ListView}}}" />
</Grid>

通过用户控件Tag属性传递ParentProp

MainPage.xaml:

<Grid Name="layoutRootGrid">
    <ListView Name="listViewParent"
                VerticalAlignment="Top"
                HorizontalAlignment="Left"
                Width="298"
                Height="458"
                Margin="42,24,0,0"
                ItemsSource="{Binding ListViewSource}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <controls:ListViewControl Tag="{Binding DataContext.ParentProp, ElementName=listViewParent}" />
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>

在您的用户控件中:

  • Name 属性 设置为 "Self" (或任何你想要的):x:Name="Self"
  • 在您的 TextBlock 中,将 Text 绑定到此用户控件的 Tag 属性

ListViewControl.xaml:

<UserControl x:Class="Namespace.ListViewControl"
                x:Name="Self"

                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Grid Background="Black"
            Name="templateGrid">
        <TextBlock Text="{Binding Path=Tag, ElementName=Self, FallbackValue='couldnt get parent prop'}"
                    VerticalAlignment="Top" />
    </Grid>
</UserControl>