[英]How to delegate a call to the ViewModel from code behind
I have a listbox and I need to do something on DoubleClick event. 我有一个列表框,我需要对DoubleClick事件进行操作。 I am able achieve this by simply using the "MouseDoubleClick" event of ListBox. 我可以通过简单地使用ListBox的“ MouseDoubleClick”事件来实现此目的。
XAML XAML
<ListBox x:Name="lbSelectedTables" AllowDrop="true" ItemsSource="{Binding SelectedTablesCollection, Mode=TwoWay}" DisplayMemberPath="Name" ItemContainerStyle="{StaticResource DraggableListBoxItem}" MouseDoubleClick="ListBox_MouseDoubleClick" SelectionMode="Multiple"></ListBox>
Code Behind 背后的代码
private void ListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
.....
My stuff here....
}
Now I would like to delegate this call to the ViewModel. 现在,我想将此调用委托给ViewModel。 How can I achieve this. 我该如何实现。
Regards, Deepak 问候,迪帕克
You can use the control's DataContext
: 您可以使用控件的DataContext
:
private void ListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
(this.DataContext as ViewModel).HandleClick(...);
}
This works if the ViewModel you want to call is the Control's ViewModel, if you want the ViewModel on which the ListBox is bound use: 如果要调用的ViewModel是控件的ViewModel,并且要绑定ListBox的ViewModel,请使用以下方法:
private void ListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
(lbSelectedTables.DataContext as ViewModel).HandleClick(...);
}
You may use galasoft MVVM light and System.Windows.Interactivity and couple the delegate directly as a command to your viewmodel, the following way. 您可以使用galasoft MVVM light和System.Windows.Interactivity,并通过以下方式将委托直接作为命令耦合到您的视图模型。 (Get MVVMLight lib only through nuget). (仅通过nuget获取MVVMLight lib)。
...
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:command="http://www.galasoft.ch/mvvmlight"
xmlns:local="clr-namespace:yournamespace"
...
<UserControl.DataContext>
<local:YourViewModel />
<UserControl.DataContext/>
<ListBox AllowDrop="true" ItemsSource="{Binding SelectedTablesCollection, Mode=TwoWay}" DisplayMemberPath="Name" ItemContainerStyle="{StaticResource DraggableListBoxItem}" SelectionMode="Multiple">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<command:EventToCommand Command="{Binding YourCommand}" PassEventArgsToCommand="True"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ListBox>
In your viewmodel: 在您的视图模型中:
public class YourViewModel: YourViewModelBaseClass {
public ICommand YourCommand{ get; set; }
public ViewModelOrCodeBehind() {
InitStuff();
}
void InitStuff(){
YourCommand = new RelayCommand<MouseButtonEventArgs>(YourMethod);
}
void YourMethod(MouseButtonEventArgs e)
{
// Do your magic here
}
}
Nice and clean with no codebehind. 干净整洁,没有任何代码隐藏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.