我在WPF中构建我的第一个MVVM应用程序。在这一刻,我试图通过双击列表框中的项目来举起活动。此事件由View处理,如下面的代码所示。
现在我想向ViewModel发送列表框中双击的项目索引。我该怎么做?
PS:ClassObject和ClassDiagram都是自定义类,它们具有相同的属性" Name"
查看
public partial class ProjectView : UserControl
{
public ProjectView()
{
InitializeComponent();
this.DataContext = new ProjectViewModel();
}
public void listBoxProject_MouseDoubleClick(object sender,MouseButtonEventArgs e)
{
MessageBox.Show(listBoxProject.SelectedIndex.ToString()); //Send index to ViewModel
}
}
XAML
<ListBox x:Name="listBoxProject" ItemsSource="{Binding CollectionList}" HorizontalAlignment="Stretch" Margin="-1,32,-1,-1" VerticalAlignment="Stretch" Width="auto" Background="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"
DisplayMemberPath="Name"
SelectedValuePath="Name"
>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource {x:Type ListBoxItem}}">
<EventSetter Event="MouseDoubleClick" Handler="listBoxProject_MouseDoubleClick"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
视图模型
namespace VITUMLEditor.ViewModels
{
public class ProjectViewModel:BaseViewModel
{
private readonly CompositeCollection collectionList = new CompositeCollection();
public ICommand AddClassCommand
{
get { return new DelegateCommand(AddClass); }
}
public ICommand AddClassDiagramCommand
{
get { return new DelegateCommand(AddClassDiagram); }
}
private void AddClass()
{
collectionList.Add(new ClassObject("Class" + ClassObject.Key, VisibilityEnum.Public));
}
private void AddClassDiagram()
{
collectionList.Add(new ClassDiagram("ClassDiagram" + ClassDiagram.Key));
}
public CompositeCollection CollectionList
{
get { return collectionList; }
}
}
}
答案 0 :(得分:-2)
In principle, you should do this with a Command. But then you've got to write code to make the double click invoke the command. The following is simple enough, and good enough for a very great number of common cases. We have dozens of these in production code and they're causing us no pain, because the view-viewmodel relationships in question are all 1:1 and will remain so. Just bear in mind that it's Impure MVVM, and can arbitrarily limit your options down the line.
Add an appropriately-named and parametered method to the viewmodel:
distance
And call it from the view:
public void ActivateItem(object item)
{
// Better if these two classes share a common base class or interface with
// a virtual function to be called in this case, but there I go ranting from
// the pulpit again.
if (item is ClassObject)
{
// Stuff
}
else if (item is ClassDiagram)
{
// Other stuff
}
}