Access property of DataContext in ItemTemplate
My datacontext has two properties: Items
which is a collection and DetailsVisiblity
which is enum of type 开发者_如何学运维Visiblity
.
On the page I have a Listbox
with ItemsSource="{Binding Entries}"
. Inside the DataTemplate
, I can bind stuff to properties of Items, but how do I get access to DetailsVisiblity
which is a property of DataContext
?
DataContext
has two properties: ObservableCollection<Item> Entries
, and Visibility DetailsVisiblity
. Item class has two properties: Title and Details.
Here is the view. How do I bind Visiblity
of the second TextBlock
to DetailsVisiblity
property?
<ListBox ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Title}" />
<TextBlock Text="{Binding Details}" Visibility="{Binding ???}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
You could name the ListBox and in the Binding you reference it with ElementName, and in Path you use DataContext.DetailsVisibility
<ListBox x:Name="listBox" ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Title}" />
<TextBlock Text="{Binding Details}"
Visibility="{Binding ElementName=listBox,
Path=DataContext.DetailsVisibilty}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
精彩评论