原文: 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的属性,所以需要用查找来找同级的对象,引用相对资源路径如下:

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

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

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄