为什么 WPF Canvas 不允许掉落?

发布于 2024-12-10 06:35:58 字数 436 浏览 0 评论 0原文

我的主窗口有以下 XAML:

<Window x:Class="ImageViewer.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   Title="Window1" Height="398" Width="434">
   <Grid>
      <Canvas AllowDrop="True" />
   </Grid>
</Window>

但是当我尝试将文件拖到窗口时,不允许放置。当 Canvas 更改为 ListBox 时,一切正常。

如何更改代码以允许拖放到画布上?

I have the following XAML for the main window:

<Window x:Class="ImageViewer.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   Title="Window1" Height="398" Width="434">
   <Grid>
      <Canvas AllowDrop="True" />
   </Grid>
</Window>

But when I try to drag a file to the window, drop is not allowed. When Canvas is changed to ListBox, everything works perfectly.

How can the code be changed to allow drop to canvas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

爱殇璃 2024-12-17 06:35:58

默认情况下,Canvas 没有背景,因此命中测试不会检测到光标位于 Canvas 元素上,而是冒泡到 Grid< /code> 或 Window 不允许放置。将背景设置为透明,如下所示,它应该可以工作:

<Window x:Class="ImageViewer.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   Title="Window1" Height="398" Width="434">
   <Grid>
      <Canvas AllowDrop="True" Background="Transparent" />
   </Grid>
</Window>

By default, Canvas has no background so hit-testing is not picking up that the cursor is over the Canvas element, but is instead bubbling up to the Grid or Window which don't allow drop. Set the background to Transparent as follows and it should work:

<Window x:Class="ImageViewer.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   Title="Window1" Height="398" Width="434">
   <Grid>
      <Canvas AllowDrop="True" Background="Transparent" />
   </Grid>
</Window>
心作怪 2024-12-17 06:35:58

这就像一个魅力!在代码中,您可能想要执行以下操作:

Canvas myCanvas = new Canvas();

myCanvas.AllowDrop = true;
myCanvas.Background = System.Windows.Media.Brushes.Transparent;

This works like a charm! In code you would want to do something such as:

Canvas myCanvas = new Canvas();

myCanvas.AllowDrop = true;
myCanvas.Background = System.Windows.Media.Brushes.Transparent;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文