我有一个图像显示在数据模板中。我想在单击图像时更改图像周围的 DataTemplate 的样式。
它曾经直接嵌套在堆栈面板中,如下所示,因此我可以通过执行以下操作轻松获取父堆栈面板。
StackPanel sp = img.Parent as StackPanel;
<StackPanel Name="uxSessionImageItem" Style="{DynamicResource RotatorItemTemplateUnselectedStyle}" Loaded="uxSessionImageItem_Loaded" >
<TextBlock Name="uxLabel" Width="150" Text="{Binding SessionImageID}" Foreground="White" VerticalAlignment="Center"/>
<Image MouseDown="ImagePanel_MouseDown" Name="uxImage" Style="{DynamicResource ItemTemplateImageStyle}" Source="{Binding ThumbPath}"/>
</StackPanel>
我必须在图像和我需要找到的堆栈面板之间添加另一个堆栈面板和边框。我需要什么语法才能找到现在作为我的父级的边框或作为边框父级的堆栈面板,而是找到该面板之上的堆栈面板?
<StackPanel Name="uxSessionImageItem" Style="{DynamicResource RotatorItemTemplateUnselectedStyle}" Loaded="uxSessionImageItem_Loaded" >
<TextBlock Name="uxLabel" Width="150" Text="{Binding SessionImageID}" VerticalAlignment="Center" Style="{DynamicResource ItemTemplateImageNumberStyle}"/>
<StackPanel Name="uxSessionImageWrapper" Style="{DynamicResource RotatorItemImageWrapperStyle}" >
<Border Name="uxImageBorder" Style="{DynamicResource ItemTemplateImageBorderStyle}">
<Image MouseDown="ImagePanel_MouseDown" Name="uxImage" Style="{DynamicResource ItemTemplateImageStyle}" Source="{Binding ThumbPath}"/>
</Border>
</StackPanel>
</StackPanel>
最佳答案
CodeNaked 的答案很好,但我不喜欢那篇文章中的代码使用递归来完成这个简单的任务,所以这里有一个修改版本,它可能可以避免堆栈溢出(不确定 WPF 是否可以嵌套)这么多,但是值得冒险吗?)
public static T FindParentOfType<T>(this DependencyObject child) where T : DependencyObject
{
DependencyObject parentDepObj = child;
do
{
parentDepObj = VisualTreeHelper.GetParent(parentDepObj);
T parent = parentDepObj as T;
if (parent != null) return parent;
}
while (parentDepObj != null);
return null;
}
关于wpf - 在 WPF 中向上导航可视化树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5954948/