今天遇到一个需求,要求能对可拖动的对象提供二种模式:允许拖动、禁止拖动。
之前的拖动为了省事,直接用了:Blend自带的MouseDragElementBehavior,于是就需要在cs代码中控制这个东东了。
折腾了一下,还算简单:
xaml代码
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(); } } } }}