Привязка данных WPF: как получить доступ к "родительскому" контексту данных?
у меня есть список (см. ниже), содержащиеся в окно. Окно-это DataContext есть два свойства, Items и AllowItemCommand.
как мне получить привязку для Hyperlink ' s Command свойство должно быть разрешено против окна DataContext?
<ListView ItemsSource="{Binding Items}">
<ListView.View>
<GridView>
<GridViewColumn Header="Action">
<GridViewColumn.CellTemplate>
<DataTemplate>
<StackPanel>
<TextBlock>
<!-- this binding is not working -->
<Hyperlink Command="{Binding AllowItemCommand}"
CommandParameter="{Binding .}">
<TextBlock Text="Allow" />
</Hyperlink>
</TextBlock>
</StackPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
3 ответа:
вы могли бы попробовать что-то вроде этого:
...Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.AllowItemCommand}" ...
это также будет работать:
<Hyperlink Command="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl}, Path=DataContext.AllowItemCommand}" />
ListViewнаследованиеDataContextСWindow, Так что это доступно на данный момент, тоже.
И с тех порListView, как и аналогичные элементы управления (например,Gridview,ListBoxи т. д.), является подклассомItemsControlнаBindingдля таких элементов управления будет работать отлично.