开发者

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜