C# 如何从FrameworkElement向事件添加ICommand?
如何从C# 如何从FrameworkElement向事件添加ICommand?,c#,xaml,mvvm,C#,Xaml,Mvvm,如何从FrameworkElement向事件添加ICommand 具体来说,我想做以下几点 我想实现我自己的解决方案,这是出于教育目的,我不希望使用任何第三方库(MVVM Light、Prism等)您需要使用附加的行为。出于演示目的,假设我想使用MVVM和ICommand模式实现按钮双击,下面是相关代码: 首先,创建一个名为ButtonBehaviors的静态类,如下所示: public static class ButtonBehaviors { public static obj
FrameworkElement
向事件添加ICommand
具体来说,我想做以下几点
我想实现我自己的解决方案,这是出于教育目的,我不希望使用任何第三方库(MVVM Light、Prism等)您需要使用附加的行为。出于演示目的,假设我想使用MVVM和ICommand模式实现按钮双击,下面是相关代码: 首先,创建一个名为ButtonBehaviors的静态类,如下所示:
public static class ButtonBehaviors
{
public static object GetButtonDoubleClick(DependencyObject obj)
{
return obj.GetValue(ButtonDoubleClickProperty);
}
public static void SetButtonDoubleClick(DependencyObject obj, object value)
{
obj.SetValue(ButtonDoubleClickProperty, value);
}
public static readonly DependencyProperty ButtonDoubleClickProperty =
DependencyProperty.RegisterAttached("ButtonDoubleClick", typeof (object), typeof (ButtonBehaviors),
new UIPropertyMetadata(new PropertyChangedCallback(OnButtonDoubleClickChanged)));
private static void OnButtonDoubleClickChanged (DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var button = d as Button;
if(button == null)
{
return;
}
var command = e.NewValue as ICommand;
if(command == null)
{
return;
}
button.MouseDoubleClick += (o, ev) => command.Execute(button);
}
}
(我马上解释)
那么,您将如何使用它:
MainWindow.xaml:
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:WpfApplication3="clr-namespace:WpfApplication3" Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="Button"
Height="23"
HorizontalAlignment="Left"
Margin="173,89,0,0"
VerticalAlignment="Top"
WpfApplication3:ButtonBehaviors.ButtonDoubleClick="{Binding ButtonDoubleClick}"
Width="75" />
</Grid>
</Window>
为了完整起见,既然你说没有第三方dll,下面是我的SimpleDelegateCommand:
public class SimpleDelegateCommand : ICommand
{
private readonly Action _action;
public SimpleDelegateCommand(Action action)
{
_action = action;
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
if(_action != null)
{
_action();
}
}
}
简而言之,发生的情况是:当您将命令分配给附加属性时,将引发OnButtonDoubleClickChanged事件,此时我们将连接到button.MouseDoubleClick事件。您的答案似乎很好,但我可以概括该事件吗?或作为参数传递
public class SimpleDelegateCommand : ICommand
{
private readonly Action _action;
public SimpleDelegateCommand(Action action)
{
_action = action;
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
if(_action != null)
{
_action();
}
}
}