今天遇到一個需求,要求能對可拖動的對象提供二種模式:允許拖動、禁止拖動。
之前的拖動為了省事,直接用了: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();
}
}
}
}
}
