开发者

Why doesn't WPF Canvas alow drop?

开发者 https://www.devze.com 2023-04-13 02:49 出处:网络
I have the following XAML for the main window: <Window x:Class=\"ImageViewer.Window1\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"

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>
开发者_Go百科</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?


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>


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号