I had a desire to get the idea of โโSteve Psaltis. It took some time - custom dependency properties are easily mistaken. It seems to me that SetXXX is the wrong place to send your side effects - WPF should not go, although it does, it can go directly to DependencyObject.SetValue , but PropertyChangedCallback will always be called.
So, here is the full and working code for the custom property:
using System.Windows; using System.Windows.Input; namespace WpfApplication1 { public static class PropertyHelper { public static readonly DependencyProperty DropCommandProperty = DependencyProperty.RegisterAttached( "DropCommand", typeof(ICommand), typeof(PropertyHelper), new PropertyMetadata(null, OnDropCommandChange)); public static void SetDropCommand(DependencyObject source, ICommand value) { source.SetValue(DropCommandProperty, value); } public static ICommand GetDropCommand(DependencyObject source) { return (ICommand)source.GetValue(DropCommandProperty); } private static void OnDropCommandChange(DependencyObject d, DependencyPropertyChangedEventArgs e) { ICommand command = e.NewValue as ICommand; UIElement uiElement = d as UIElement; if (command != null && uiElement != null) { uiElement.Drop += (sender, args) => command.Execute(args.Data); }
In the XAML markup where you want to use this, you can do, for example.
xmlns:local="clr-namespace:WpfApplication1" ... <Button Content="Drop here" Padding="12" AllowDrop="True" local:PropertyHelper.DropCommand="{Binding DropCommand}" />
.. And the rest is just to make sure your ViewModel, bindings and command are right.
This version passes IDataObject through a command that seems better to me - you can request it for files or anything in the command. But this is only the current preference, and not an essential characteristic of the answer.
Anthony
source share