WPF之实现控件内容拖动

 以下分别记录label、listbox、treeview三个控件的拖动示例:

1.对被拖动控件,实现拖动事件,主要是通过各种鼠标事件,实现DragDrop.DoDragDrop方法。

2.对于需要拖动到的目的控件,需要实现AllowDrop=”True” Drop=”TargetLabel_Drop”

   <Window.Resources>
        <Style TargetType="ListBoxItem">
            <EventSetter Event="PreviewMouseMove" Handler="ListBox_PreviewMouseMove"/>
        </Style>
        <Style TargetType="TreeViewItem">
            <EventSetter Event="PreviewMouseMove" Handler="TreeView_PreviewMouseMove"/>
        </Style>
      
    </Window.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="7*"/>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="3*"/>
        </Grid.ColumnDefinitions>
        <StackPanel>
            <Label Name="Label" Margin="5,10" Content="This is Label" MouseDown="Label_MouseDown"/>
            <ListBox Margin="5,10">
                <ListBoxItem>000</ListBoxItem>
                <ListBoxItem>111</ListBoxItem>
                <ListBoxItem>222</ListBoxItem>
            </ListBox>
            <TreeView Name="treeView" Margin="5,10">
                <TreeViewItem Header="aa">
                    <TreeViewItem Header="00"/>
                    <TreeViewItem Header="11"/>
                    <TreeViewItem Header="22"/>
                </TreeViewItem>
            </TreeView>
            <Button Height="30" Margin="5,10" Name="btn" Content="Rest" Click="btn_Click"/>
        </StackPanel>
        <Rectangle Grid.Column="1" Fill="Red" Width="1"/>
        <Label Name="TargetLabel" Grid.Column="2" Content="Come here"  Background="AliceBlue" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" AllowDrop="True" Drop="TargetLabel_Drop"/>
    </Grid>
  private void TargetLabel_Dropobject sender, DragEventArgs e)
        {
            var txt = e.Data.GetDataDataFormats.Text);
            this.TargetLabel.Content = txt;
        }

        private void btn_Clickobject sender, RoutedEventArgs e)
        {
            this.TargetLabel.Content = "Come here";
        }

        private void Label_MouseDownobject sender, MouseButtonEventArgs e)
        {
            DragDrop.DoDragDropLabel, Label.Content, DragDropEffects.Copy);
        }

        private void ListBox_PreviewMouseMoveobject sender, MouseEventArgs e)
        {
            var item = sender as ListBoxItem;
            DragDrop.DoDragDropitem, item.Content, DragDropEffects.Copy);
        }

        private void TreeView_PreviewMouseMoveobject sender, MouseEventArgs e)
        {
            if e.LeftButton==MouseButtonState.Released)
            {
                return;
            }

            var t = sender as TreeView;
            var x = this.treeView.SelectedItem;
            if x==null)
            {
                return;
            }
            var item = x as TreeViewItem;
            DragDrop.DoDragDropitem, item.Header, DragDropEffects.Copy);
        }

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注