我有一个用户控件,在页面中用作DataTemplate。 WP8 - access datacontext of parent中存在类似问题的响应,但DataTemplate定义为“内部”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的集合和属性 - listViewParent的DataContext):
<Grid Background="Black" Name="templateGrid">
<TextBlock Text="{Binding DataContext.ParentProp, ElementName=listViewParent, FallbackValue='couldnt get parent prop'}" VerticalAlignment="Top"/>
</Grid>
答案 0 :(得分:1)
将ParentProp
传递给用户控件的Tag
属性
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>
答案 1 :(得分:0)
您应该能够绑定到父数据上下文,如下所示:
<Grid Background="Black" Name="templateGrid">
<TextBlock Text="{Binding DataContext.ParentProp, RelativeSource={RelativeSource AncestorType={x:Type ListView}}}" />
</Grid>