WPF实现拖拽功能

技术点:WPF的Behaviors实现了对象的行为附加,Microsoft.Expression.Interactions程序集中包含了若干Behaviors,其中MouseDragElementBehavior可以实现对象拖拽行为的附加,从而实现对象的拖拽功能。

代码如下:

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp6"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" x:Class="WpfApp6.MainWindow"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Label Content="拖我" HorizontalAlignment="Left" Margin="138.762,47.137,0,0" VerticalAlignment="Top">
            <i:Interaction.Behaviors>
                <ei:MouseDragElementBehavior/>
            </i:Interaction.Behaviors>
        </Label>
        <Label Content="拖我" HorizontalAlignment="Left" Margin="252.741,89.735,0,0" VerticalAlignment="Top">
            <i:Interaction.Behaviors>
                <ei:MouseDragElementBehavior/>
            </i:Interaction.Behaviors>
        </Label>
        <Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="22.862" Margin="59.322,159.513,0,0" VerticalAlignment="Top" Width="100">
            <i:Interaction.Behaviors>
                <ei:MouseDragElementBehavior/>
            </i:Interaction.Behaviors>
        </Border>
        <Grid HorizontalAlignment="Left" Height="42.434" Margin="219.356,159.513,0,0" VerticalAlignment="Top" Width="111.513" Background="Black">
            <i:Interaction.Behaviors>
                <ei:MouseDragElementBehavior/>
            </i:Interaction.Behaviors>
        </Grid>
        <Grid HorizontalAlignment="Left" Height="42.434" Margin="372.481,159.513,0,0" VerticalAlignment="Top" Width="111.513" Background="Black">
            <i:Interaction.Behaviors>
                <ei:MouseDragElementBehavior/>
            </i:Interaction.Behaviors>
            <Button Content="Button拖不了" HorizontalAlignment="Left" VerticalAlignment="Top" Width="91.709" Foreground="Black" Margin="9.804,13.194,0,0" Background="White">
            </Button>
        </Grid>
    </Grid>
</Window>

运行效果:

 【代码

posted @ 2018-02-13 09:45  Perfectionist  阅读(927)  评论(0编辑  收藏  举报