我将带有 Canvas 的 ItemsControl 作为 ItemsPanelTemplate 绑定(bind)到 ObservableCollection。
我想使用 DraggableExtender 使项目可拖动,如中发布的 Dragging an image in WPF (我不想使用变换 - 我需要使用 Canvas Left 和 Top 属性)
它的定义是:
<ItemsControl ItemsSource="{Binding Path=Nodes}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas IsItemsHost="True" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Views:NodeView DataContext="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Utilities:DraggableExtender.CanDrag" Value="True" />
<Setter Property="Canvas.Left" Value="{Binding Path=X}" />
<Setter Property="Canvas.Top" Value="{Binding Path=Y}" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
DraggableExtender需要元素的父元素是Canvas, 但我的元素(contentpresenter)的父元素为空,因此拖动不起作用。
所以显而易见的问题是 - 我做错了什么?
最佳答案
由于项目并不直接位于 Canvas 内,因此您需要沿着视觉树向上移动,直到找到 Canvas 。我通常使用以下扩展方法来做到这一点:
public static T FindAncestor<T>(this DependencyObject obj)
where T : DependencyObject
{
DependencyObject tmp = VisualTreeHelper.GetParent(obj);
while(tmp != null && !(tmp is T))
{
tmp = VisualTreeHelper.GetParent(tmp);
}
return tmp as T;
}
将上面的方法放在静态类中,并导入声明它的命名空间。在 DraggableExtender
代码中,只需替换这一行:
Canvas canvas = element.Parent as Canvas;
有了这个:
Canvas canvas = element.FindAncestor<Canvas>();
关于wpf - 将 ItemsControl 与可拖动项目组合 - Element.parent 始终为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3902392/