我的ListView控件有DataTemplate,它包含很少的文本块和一个按钮。我希望只有在选择项目时才能看到该按钮。 这是我的DataTemplate代码:
<ListView.ItemTemplate>
<DataTemplate>
<Grid Background="AliceBlue">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="90" />
</Grid.ColumnDefinitions>
<TextBlock HorizontalAlignment="Left" Margin="10,0,10,0"
VerticalAlignment="Center" FontFamily="Verdana" FontSize="16"
FontWeight="Black" Grid.Column="0" Text="{Binding name}"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Grid.Column="1">
<TextBlock FontFamily="Verdana" FontSize="10" Grid.Column="1"
VerticalAlignment="Center" HorizontalAlignment="Center"
Text="Number of Chapters: " />
<TextBlock FontFamily="Verdana" FontSize="12" Grid.Column="1"
VerticalAlignment="Center" HorizontalAlignment="Center"
Text="{Binding chaptersCount}" />
</StackPanel>
<Button HorizontalAlignment="Center" Height="50" Width="80" Content="Read"
Grid.Column="2" Visibility="Hidden" Click="Button_Click_3" Name="ReadButton"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
我该怎么做?
答案 0 :(得分:2)
您可以使用DataTemplate中的 DataTrigger
来实现此功能,该功能将检查模板化父级的 IsSelected
属性:
<ListView.ItemTemplate>
<DataTemplate>
.....
<Button HorizontalAlignment="Center" Height="50"
Width="80" Content="Read"
Grid.Column="2" Visibility="Hidden" Name="ReadButton"/>
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsSelected,
RelativeSource={RelativeSource Mode=TemplatedParent}}"
Value="True">
<Setter TargetName="ReadButton" Property="Visibility"
Value="Visible"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListView.ItemTemplate>
答案 1 :(得分:0)
您需要稍微更改按钮:快速XAML方式是在Trigger
上添加Visibility
以使其在未选中时隐藏(注意:代码写在这里,希望没有拼写错误):
<Button HorizontalAlignment="Center" Height="50" Width="80" Content="Read"
Grid.Column="2" Click="Button_Click_3" Name="ReadButton">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}" Value="False">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>