C# 如何在WPF的ViewModel中绑定Drop和PreviewMouseLeftButtonDown事件
我必须在ViewModel中绑定Grid Drop事件和PreviewMouseLeftButtonDown事件。我有一个休闲社区。但它只用于传递对象,我必须使用命令传递routed事件,也用于MouseButtonEventArgs。我的示例代码如下,请给出在viewmodel中使用路由事件参数和MouseButtonEventArgs的建议C# 如何在WPF的ViewModel中绑定Drop和PreviewMouseLeftButtonDown事件,c#,wpf,xaml,mvvm,mouseevent,C#,Wpf,Xaml,Mvvm,Mouseevent,我必须在ViewModel中绑定Grid Drop事件和PreviewMouseLeftButtonDown事件。我有一个休闲社区。但它只用于传递对象,我必须使用命令传递routed事件,也用于MouseButtonEventArgs。我的示例代码如下,请给出在viewmodel中使用路由事件参数和MouseButtonEventArgs的建议 <Grid x:Name="mainGrid"
<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">
我觉得对于这样简单的任务,命令往往是多余的。 您只需在视图的代码隐藏中声明ViewModel,如下所示:
public partial class MainWindow : Window
{
private ViewModel _vm;
public ViewModel Vm
{
get { return _vm;}
set
{
_vm = value ;
}
}
//....Constructor here....
}
然后创建一个公共事件:
public event RoutedEventHandler OnGridDrop;
打电话进来:
public void Grid_Drop(object sender, RoutedEventArgs e)
{
OnGridDrop?.Invoke(sender,e)
}
现在,您只需初始化ViewModel:
public MainWindow()
{
InitializeComponent();
Vm = new ViewModel();
OnGridDrop += Vm.OnGridDrop;
}
并订阅您在ViewModel中声明的相应处理程序。投票的可能重复关闭此操作,因为它是重复的,简短的回答是您还可以使用RelayCommand的通用版本,该版本接受特定类型,并使用EventToCommand之类的内容绑定到它(假设您使用的是MVVM Lite)。如果您不想使用事件参数类型本身,也可以使用带有转换器的EventArgsConverter将其更改为您需要的任何内容。@MarkFeldman,我没有使用MVVM light。我试试你的link@MarkFeldman,在您的链接中,接受的答案包含(cmd:EventToCommand)引用,但EventToCommand未被解释。我搜索了很多网站,但EventToCommand不在那里。请帮助了解如何完成EventToCommand。EventToCommand内置于许多MVVM库中,包括MVVM Lite。一个简单的Google将返回源代码,包括。
public void Grid_Drop(object sender, RoutedEventArgs e)
{
OnGridDrop?.Invoke(sender,e)
}
public MainWindow()
{
InitializeComponent();
Vm = new ViewModel();
OnGridDrop += Vm.OnGridDrop;
}