拖放WPF组合框,按钮,单选按钮等

时间:2011-08-03 14:54:02

标签: wpf drag-and-drop

我有一个问题,我已经阅读过有关WPF拖放的教程,博客等(我正在使用VS10)。

问题是我需要一个带按钮,组合框,单选按钮等的工具箱,用户可以将其拖放到工作区(画布或其他任何东西)上并将其拖放(复制)。

我设法从文本框和图像拖放,但这对我不起作用,当我尝试按钮或组合框它只是不起作用,我认为它是默认的点击事件的原因,我不'知道问题是什么。这是我用按钮试过的。

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <TextBox Height="22" HorizontalAlignment="Left" Margin="84,36,0,0" Name="textBox1" VerticalAlignment="Top" Width="103" Text="Drag" />
    <TextBox Height="40" HorizontalAlignment="Left" Margin="225,136,0,0" Name="textBox3" VerticalAlignment="Top" Width="124" Text="Drop" />
    <Label Content="DragLabel" Height="26" HorizontalAlignment="Left" Margin="284,36,0,0" Name="label1" VerticalAlignment="Top" Width="80" MouseDown="label1_MouseDown" />
    <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="84,122,0,0" Name="button1" VerticalAlignment="Top" Width="75" MouseDown="button1_MouseDown" AllowDrop="True" IsEnabled="True" Click="button1_Click" />
    <Rectangle Height="100" HorizontalAlignment="Left" Margin="149,199,0,0" Name="rectangle1" Stroke="Black" VerticalAlignment="Top" Width="200" AllowDrop="True" Fill="#FFDCA1A1" />
</Grid>

我的代码背后......

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void label1_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Label lbl = (Label)sender;
            DragDrop.DoDragDrop(lbl, lbl.Content, DragDropEffects.Copy);
        }


        private void button1_MouseDown(object sender, MouseButtonEventArgs e)
        {
            var dependencyObject = (Button)sender;
            DragDrop.DoDragDrop(dependencyObject, dependencyObject, DragDropEffects.Move);
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            return;
        }
    }

提前谢谢你们。顺便问一下我的英语:s ...

再来一次!

路易斯

2 个答案:

答案 0 :(得分:1)

您是否尝试使用PreviewMouseDown事件代替MouseDown?在Button捕获点击之前,您的代码将被调用。

WPF元素通常使用RoutedEvents,它通常具有使用Tunneling Routing Strategy的相应“预览”事件,该事件将在实际引发事件的元素之前发送给所有父项。这样,您就可以执行操作以响应MouseDown 之前 Button有机会尝试执行点击操作。

答案 1 :(得分:1)

private void button1_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    var dependencyObject = (Button)sender;
    DragDrop.DoDragDrop(dependencyObject, dependencyObject, DragDropEffects.Move); 
} 

将如 Abe

所述