ListBox项模板中绑定ListBoxItem属性的方法

<ListBox>
	<ListBox.ItemTemplate>
		<DataTemplate>
			<Grid Width="225"  Height="126" FocusVisualStyle="{x:Null}">
				<TextBlock 
					x:Name="sortIndex"
					FontFamily="微软雅黑" FontSize="18" Foreground="Black"
					HorizontalAlignment="Left" VerticalAlignment="Top"
					Text="test"/>
			</Grid>
			<DataTemplate.Triggers>
				<DataTrigger Binding="{Binding Path=IsSelected, RelativeSource={RelativeSource Mode=FindAncestor,AncestorLevel=1,AncestorType={x:Type ListBoxItem}}}" Value="True">
					<Setter Property="Foreground" TargetName="sortIndex" Value="White"/>
				</DataTrigger>
			</DataTemplate.Triggers>
		</DataTemplate>
	</ListBox.ItemTemplate>
</ListBox>

因为在数据模板中没办法找ListBoxItem的属性,所以需要用查找来找同级的对象,引用相对资源路径如下:

RelativeSource={RelativeSource Mode=FindAncestor,AncestorLevel=1,AncestorType={x:Type ListBoxItem}}

猜你喜欢

转载自blog.csdn.net/FireGhost57/article/details/88952315
今日推荐