WPF 附加属性
最近在学习WPF,虽其依赖属性非常优美,而附加属性更为漂亮,以此已记之:
主要实现label双击事件
先定义所需要的附加属性
public class MDCTest
{
public static DependencyProperty MouseDoubleClickCommandProperty = DependencyProperty.RegisterAttached(
"MouseDoubleClick",
typeof(ICommand),
typeof(MDCTest),
new FrameworkPropertyMetadata(null, new PropertyChangedCallback(MouseDoubleClickChanged))
);
public static void SetMouseDoubleClick(DependencyObject target, ICommand value)
{
target.SetValue(MDCTest.MouseDoubleClickCommandProperty, value);
}
public static ICommand GetMouseDoubleClick(DependencyObject target)
{
return (ICommand)target.GetValue(MDCTest.MouseDoubleClickCommandProperty);
}
private static void MouseDoubleClickChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
{
Control control = target as Control;
if (control != null)
{
if (e.NewValue != null && e.OldValue == null)
{
control.MouseDoubleClick += new MouseButtonEventHandler(control_MouseDoubleClick);
}
else if (e.NewValue == null && e.OldValue != null)
{
control.MouseDoubleClick -= new MouseButtonEventHandler(control_MouseDoubleClick);
}
}
}
public static void control_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
Control control = sender as Control;
ICommand command = (ICommand)control.GetValue(MDCTest.MouseDoubleClickCommandProperty);
command.Execute(control);
}
}
然后实现ICommand接口
public class RelayCommand : ICommand
{
private Action<object> _Execute;
private Predicate<object> _CanExecute;
public RelayCommand(Action<object> execte)
: this(execte, null)
{
}
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("Execute");
_Execute = execute;
_CanExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _CanExecute == null ? true : _CanExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_Execute(parameter);
}
}
接在定义viewmodel(旨在实现这个附加属性,所以比较简单)
public class LabelViewModel
{
public ICommand Command
{
get
{
return new RelayCommand((m) => MessageBox.Show(m.ToString() + "command双击事件成功"));
}
}
}
最后为前台显示
<Label Name="label" local:MDCTest.MouseDoubleClick="{Binding Path=Command}">MouseDoubleClickTest</Label>