Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Diagnostics;
- using System.Linq;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Input;
- namespace UI.Behaviors
- {
- /// <summary>
- /// Behavoir to handle elements Mouse Down Event
- /// <remarks>
- /// bhv:MouseDownBehavior.Command="{Binding MouseDownCommand}"
- /// bhv:MouseDownBehavior.UsePreviewMouseDown="True"
- /// </remarks>
- /// </summary>
- public static class MouseDownBehavior
- {
- #region Command Dependency Property
- public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached(
- "Command",
- typeof(ICommand),
- typeof(MouseDownBehavior),
- new UIPropertyMetadata(null, OnCommandChanged));
- public static ICommand GetCommand(DependencyObject obj)
- {
- return (ICommand)obj.GetValue(CommandProperty);
- }
- public static void SetCommand(DependencyObject obj, ICommand value)
- {
- obj.SetValue(CommandProperty, value);
- }
- #endregion
- #region UsePreviewMouseDown Dependency Property
- public static readonly DependencyProperty UsePreviewMouseDownProperty = DependencyProperty.RegisterAttached(
- "UsePreviewMouseDown",
- typeof(bool),
- typeof(MouseDownBehavior),
- new UIPropertyMetadata(false));
- public static bool GetUsePreviewMouseDown(DependencyObject obj)
- {
- return (bool)obj.GetValue(UsePreviewMouseDownProperty);
- }
- public static void SetUsePreviewMouseDown(DependencyObject obj, bool value)
- {
- obj.SetValue(UsePreviewMouseDownProperty, value);
- }
- #endregion
- static void OnCommandChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
- {
- var ele = sender as UIElement;
- if (ele == null)
- return;
- if (args.OldValue != null)
- {
- if (GetUsePreviewMouseDown(ele))
- ele.PreviewMouseDown -= OnMouseDown;
- else
- ele.MouseDown -= OnMouseDown;
- }
- if (args.NewValue != null)
- {
- if (GetUsePreviewMouseDown(ele))
- ele.PreviewMouseDown += OnMouseDown;
- else
- ele.MouseDown += OnMouseDown;
- }
- }
- static void OnMouseDown(object sender, MouseButtonEventArgs e)
- {
- var ele = sender as UIElement;
- if (ele == null)
- return;
- var command = GetCommand(ele);
- if (command != null)
- {
- if (command.CanExecute(e))
- {
- command.Execute(e);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement