WPF:为什么我的 DataTemplate 项找不到其父项?
我的 *.xaml 中有一个 DataTemplate,它是我的列表视图控件的数据模板:
<DataTemplate x:Key="listViewSourceItemTemplate" DataType="{x:Type this:SourceItemField}">
<this:SourceItemField Background="LightPink">
<i:Interaction.Behaviors>
<ei:MouseDragElementBehavior/>
</i:Interaction.Behaviors>
<StackPanel Orientation="Horizontal" Margin="5,10,5,10" Background="LightGray">
<TextBlock Text="{Binding Path=FieldType,StringFormat=\{0\}}" Margin="0,0,5,0" />
<TextBlock Text="{Binding Path=ContextName,StringFormat=\{0\}}" Margin="0,0,5,0" />
<TextBlock Text="{Binding Path=FieldName,StringFormat=\{0\}}" Margin="0,0,5,0" />
<TextBlock Text="{Binding Path=ConnectionNumber,StringFormat=\{0\}}" Margin="0,0,5,0" />
</StackPanel>
</this:SourceItemField>
在我的 C# 代码中,我有以下程序:
public void SetPosition()
{
Center = this.TransformToAncestor(FindAncestor<Canvas>(this)).Transform(new Point(this.ActualWidth / 2, this.ActualHeight / 2));
}
// walk up the visual tree for parent of type T
private static T FindAncestor<T>(DependencyObject current)
where T : DependencyObject
{
do
{
if (current is T)
{
return (T)current;
}
current = VisualTreeHelper.GetParent(current);
}
while (current != null);
return null;
}
“this”是 SourceItemField,为什么 VisualTreeHelper.GetParent() 将其祖先返回为“null”?为什么这个 SourceItemField 的父级不是我的列表视图?
I have a DataTemplate in my *.xaml, it is the datatemplate for my listview control:
<DataTemplate x:Key="listViewSourceItemTemplate" DataType="{x:Type this:SourceItemField}">
<this:SourceItemField Background="LightPink">
<i:Interaction.Behaviors>
<ei:MouseDragElementBehavior/>
</i:Interaction.Behaviors>
<StackPanel Orientation="Horizontal" Margin="5,10,5,10" Background="LightGray">
<TextBlock Text="{Binding Path=FieldType,StringFormat=\{0\}}" Margin="0,0,5,0" />
<TextBlock Text="{Binding Path=ContextName,StringFormat=\{0\}}" Margin="0,0,5,0" />
<TextBlock Text="{Binding Path=FieldName,StringFormat=\{0\}}" Margin="0,0,5,0" />
<TextBlock Text="{Binding Path=ConnectionNumber,StringFormat=\{0\}}" Margin="0,0,5,0" />
</StackPanel>
</this:SourceItemField>
In my C# code, I have following program:
public void SetPosition()
{
Center = this.TransformToAncestor(FindAncestor<Canvas>(this)).Transform(new Point(this.ActualWidth / 2, this.ActualHeight / 2));
}
// walk up the visual tree for parent of type T
private static T FindAncestor<T>(DependencyObject current)
where T : DependencyObject
{
do
{
if (current is T)
{
return (T)current;
}
current = VisualTreeHelper.GetParent(current);
}
while (current != null);
return null;
}
"this" is SourceItemField, why VisualTreeHelper.GetParent() return its ancestor as "null"? Why this SourceItemField's parent is not my listview?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您确定要查找 Canvas 而不是 ListView 作为祖先吗?
即而不是这个:
这个:
Are you sure you want to find Canvas and not the ListView as ancestor?
i.e. instead of this:
this: