【发布时间】:2018-07-17 08:56:12
【问题描述】:
我必须在 ViewModel 中绑定 Grid Drop 事件和 PreviewMouseLeftButtonDown 事件。我有一个 RelayCommand。但它仅用于传递对象,我必须使用命令传递路由事件,也用于 MouseButtonEventArgs。我的示例代码如下,请对在视图模型中使用路由事件参数和 MouseButtonEventArgs 提出任何建议。
<Grid
x:Name="mainGrid"
AllowDrop="True"
Background="#F0F0F0">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Drop">
<cmd:EventCommandExecuter Command="{Binding GridDrop}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Grid>
<Grid Background="LightBlue" PreviewMouseLeftButtonDown="Grid_PreviewMouseLeftButtonDown">
EventCommandExecuter
public class EventCommandExecuter : TriggerAction<DependencyObject>
{
#region Constructors
public EventCommandExecuter()
: this(CultureInfo.CurrentCulture)
{
}
public EventCommandExecuter(CultureInfo culture)
{
Culture = culture;
}
#endregion
#region Properties
#region Command
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register("Command", typeof(ICommand), typeof(EventCommandExecuter), new PropertyMetadata(null));
#endregion
#region EventArgsConverterParameter
public object EventArgsConverterParameter
{
get { return (object)GetValue(EventArgsConverterParameterProperty); }
set { SetValue(EventArgsConverterParameterProperty, value); }
}
public static readonly DependencyProperty EventArgsConverterParameterProperty =
DependencyProperty.Register("EventArgsConverterParameter", typeof(object), typeof(EventCommandExecuter), new PropertyMetadata(null));
#endregion
public IValueConverter EventArgsConverter { get; set; }
public CultureInfo Culture { get; set; }
#endregion
protected override void Invoke(object parameter)
{
var cmd = Command;
if (cmd != null)
{
var param = parameter;
if (EventArgsConverter != null)
{
param = EventArgsConverter.Convert(parameter, typeof(object), EventArgsConverterParameter, CultureInfo.InvariantCulture);
}
if (cmd.CanExecute(param))
{
cmd.Execute(param);
}
}
}
}
我想在视图模型中传递对象和 RoutedEventArgs,如下所示。请帮忙
public void Grid_Drop(object sender, RoutedEventArgs e)
{
}
【问题讨论】:
-
投票关闭它,因为它是重复的,简短的回答是您还可以使用通用版本的 RelayCommand 接受特定类型并使用 EventToCommand 之类的东西绑定到它(假设您使用的是 MVVM Lite )。如果您不想使用事件参数类型本身,您还可以使用带有转换器的 EventArgsConverter 将其更改为您需要的任何内容。
-
@MarkFeldman,我没有使用 MVVM 灯。我试试你的链接
-
@MarkFeldman,在您的链接中,接受的答案包含 (cmd:EventToCommand) 参考,但 EventToCommand 没有解释。我搜索了很多网站,但 EventToCommand 不存在。请帮助如何完成 EventToCommand。
-
EventToCommand 内置于众多 MVVM 库中,包括 MVVM Lite。一个简单的谷歌会返回包含here的源代码。
标签: c# wpf xaml mvvm mouseevent