Binding to the IsSelected property of the parent L

2019-04-04 15:36发布

I'm attempting to bind the Visibility property of a TextBlock that's held within the ItemTemplate for a ListView to the IsSelected property of the TextBlock's parent ListViewItem.

With this markup, the TextBlock is always visible.

<ListView x:Name="ItemListView" ItemsSource="{Binding Path=Accounts}" Margin="60,0,0,10" Grid.Row="1" Grid.Column="0">
    <ListView.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="100">
                    </ColumnDefinition>
                    <ColumnDefinition Width="*"></ColumnDefinition>
                    <ColumnDefinition Width="200"></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <Image Width="100" Height="100" Grid.Column="0"></Image>
                <StackPanel Grid.Column="1">
                    <TextBlock Text="{Binding Path=Account.Name}"  
                                FontSize="24" Margin="5,0,0,0" TextWrapping="Wrap" />
                </StackPanel>
                <TextBlock Grid.Column="3" VerticalAlignment="Bottom"
                            Visibility="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=IsSelected, Converter={StaticResource boolConverter}, Mode=OneWay}">
                    Show More Details...
                </TextBlock>
            </Grid>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Notes: 1. In case it makes any difference, this is WinRT; a Metro app written in C#. 2. boolConverter is a fairly standard converter appears to work correctly.

3条回答
【Aperson】
2楼-- · 2019-04-04 15:58

@Murven 's answer was close. This is what worked for me:

<TextBlock Visibility="{Binding DataContext.IsSelected, ElementName=ItemListView Converter={StaticResource boolConverter}, Mode=OneWay}">

I had to use DataContext.IsSelected to access the context of the ItemListView. Not sure if there is a better way.

查看更多
三岁会撩人
3楼-- · 2019-04-04 16:09

I think that in this case you will have to use ElementName=ItemListView

查看更多
Fickle 薄情
4楼-- · 2019-04-04 16:14

Use Mode=FindAncestor:

<TextBlock Grid.Column="3" VerticalAlignment="Bottom"
          Visibility="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListViewItem}, Path=IsSelected, Converter={StaticResource boolConverter}, Mode=OneWay}">
查看更多
登录 后发表回答