Why doesn't WPF Canvas alow drop?

爷,独闯天下 提交于 2019-12-19 17:37:47

问题


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?


回答1:


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>



回答2:


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;


来源:https://stackoverflow.com/questions/7762957/why-doesnt-wpf-canvas-alow-drop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!