我有一个自定义控件,其中包含一个事件。 我有一个使用该自定义控件的窗口。 该窗口绑定到一个视图模型。 我希望将自定义控件的事件直接传递给视图模型上的ICommand。 显然,我很迟钝,无法想出如何做到这一点。任何帮助都非常欢迎。
谢谢
<some:CustomControl SuperDuper="OnSuperDuper" />
private void OnSuperDuper(object sender, EventArgs e)
{
_theCommand.Execute(null, (IInputElement)sender);
}
<some:CustomControl my:AttachedEvents.SuperDuperCommand="{Binding TheCommand}" />
所附加的属性仅为:
// use propa snippet to build this quickly
public static ICommand GetSuperDuperCommand(DependencyObject obj) { return (ICommand)obj.GetValue(SuperDuperCommandProperty); }
public static void SetSuperDuperCommand(DependencyObject obj, ICommand value) { obj.SetValue(SuperDuperCommandProperty, value); }
public static readonly DependencyProperty SuperDuperCommandProperty = DependencyProperty.RegisterAttached("SuperDuperCommand", typeof(ICommand), typeof(AttachedEvents), new PropertyMetadata
{
PropertyChangedCallback = (obj, e) =>
{
if(oldCommand==null) ((CustomControl)obj).SuperDuper += OnSuperDuper;
if(newCommand==null) ((CustomControl)obj).SuperDuper -= OnSuperDuper;
}
});
private void OnSuperDuper(object sender, EventArgs e)
{
var control = (CustomControl)sender;
GetSuperDuperCommand(sender).Execute(null, sender));
}
您可以进一步推广此方法,使用MarkupExtension将任何事件映射到任何命令。 这是个想法:
<some:CustomControl SuperDuper="{lib:CommandWrapper {Binding TheCommand}}" />
public class CommandWrapper : MarkupExtension
{
public BindingBase CommandBinding { get; set; }
public CommandWrapper() {}
public CommandWrapper(BindingBase commandBinding) { CommandBinding = commandBinding; }
public object ProvideValue(IServiceProvider serviceProvider)
{
return new EventHandler((obj, e) =>
{
// Evaluate CommandBinding against obj, fire command
});
}
}
<some:CustomControl lib:CommandWrapper.Add="{lib:CommandWrapper SuperDuper,{Binding TheCommand}}" />
如果您想将事件路由到命令,则可以使用附加属性。我使用此示例将命令支持添加到ComboBox SelectionChanged事件:
http://blog.fossmo.net/post/How-to-create-an-attached-property-in-WPF-using-a-ComboBox.aspx
干杯。