这与我正在实现的一些自定义拖放功能有关。
在我将 ContentPresenter 加入其中之前,一切都运行良好。
我有一个包含 ContentPresenter 的窗口。
这个 ContentPresenter 的内容绑定了动态弹出和弹出的不同用户控件。
我遇到的问题是我需要对 ContentPresenter 中包含的控件执行 TransformToVisual ,该控件相对于位于此 COntentPresenter 所在的主窗口之外的控件。
概括:
Window -> Canvas 称为 MyCanvas -> ContenPresenter(Content Presenter 包含一个名为 MyListView 的 ListView)
我想调用 MyListView.TransformToVisual(MyCanvas)。
这似乎是不允许的,因为我收到错误消息:“指定的 Visual 和此 Visual 不共享共同的祖先,因此两个 Visual 之间没有有效的转换。”
以下片段的注释: 1. _targetBoundingBoxes 是一个 UIElements 列表,它应该接受拖动 2. 当我拖动时,我在屏幕上移动了一个画布 (_canvasThatIsBeingDraggedAround)。3. 当它移动时,我正在查询当前 MousePosition 是否落在任何 _dropTargets 内。
失败的代码片段:
_targetBoundingBoxes.Clear();
foreach (var item in _dropTargets)
{
GeneralTransform t = item.TransformToVisual(_canvasThatIsBeingDraggedAround);
Rect _dropBoundingBox = t.TransformBounds(new Rect(0, 0, item.RenderSize.Width, item.RenderSize.Height));
_targetBoundingBoxes.Add(item, _dropBoundingBox);
}
<Window>
<StackPanel>
<Button Margin="0,50,0,0" Height="50"/>
<ContentPresenter Name="HI" Content="{Binding Blah}"/>
</StackPanel>
</Window>
//Create a canvas which will be used as the dragged adorner. Canvas is used since you can set the Left and Top positions.
if (_topWindow.FindName("adornerLayer") == null)
{
//grab the existingContent
UIElement existingContent = (UIElement)_topWindow.Content;
//create a Grid wrapper around the entire window content so we can add the new canvas adornerLayer as a child in addition to the existing content
Grid nonLayoutCanvas = new Grid(); nonLayoutCanvas.VerticalAlignment = VerticalAlignment.Stretch; nonLayoutCanvas.HorizontalAlignment = HorizontalAlignment.Stretch;
//create the hidden Canvas that we will draw to and move around the screen
Canvas adornerCanvas = new Canvas(); adornerCanvas.Visibility = Visibility.Collapsed; adornerCanvas.Name = "adornerLayer";
adornerCanvas.Effect = new DropShadowEffect() { ShadowDepth = 5, BlurRadius = 5, Color = Colors.Silver };
//reset the content to the nonLayout Canvas
_topWindow.Content = nonLayoutCanvas;
//add the original content and the new canvas to the grid above
nonLayoutCanvas.Children.Add(existingContent);
nonLayoutCanvas.Children.Add(adornerCanvas);
_topWindow.RegisterName("adornerLayer", adornerCanvas);
}
_canvasThatIsBeingDraggedAround = (Canvas)_topWindow.FindName("adornerLayer");