今天遇到一个需求,要求能对可拖动的对象提供二种模式:允许拖动、禁止拖动。
之前的拖动为了省事,直接用了:Blend自带的MouseDragElementBehavior,于是就需要在cs代码中控制这个东东了。
折腾了一下,还算简单:
xaml代码
<UserControl 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:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" x:Class="slTest.MainPage" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400"> <Grid x:Name="LayoutRoot" Background="White"> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition MinHeight="22" Height="Auto"/> </Grid.RowDefinitions> <Canvas Background="Navy" x:Name="c" Cursor="Hand"> <i:Interaction.Behaviors> <ei:MouseDragElementBehavior/> </i:Interaction.Behaviors> <TextBlock Foreground="White" FontSize="24">点击拖动Canvas</TextBlock> </Canvas> <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Center" Margin="0,5"> <Button Width="80" Content="允许拖动" x:Name="btnEnable" Click="btnEnable_Click"/> <Button Width="80" Content="禁止拖动" Margin="5,0,0,0" x:Name="btnDisable" Click="btnDisable_Click"/> </StackPanel> </Grid> </UserControl>
xaml.cs代码
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Interactivity; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Expression.Interactivity; using Microsoft.Expression.Interactivity.Layout; namespace slTest { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); } private void btnEnable_Click(object sender, RoutedEventArgs e) { var behaviorsCollection = Interaction.GetBehaviors(c); if (behaviorsCollection.Count>0) { var behavior = behaviorsCollection[0] as MouseDragElementBehavior; if (behavior!=null){ behavior.Attach(c); } } } private void btnDisable_Click(object sender, RoutedEventArgs e) { var behaviorsCollection = Interaction.GetBehaviors(c); if (behaviorsCollection.Count > 0) { var behavior = behaviorsCollection[0] as MouseDragElementBehavior; if (behavior!=null){ behavior.Detach(); } } } } }