【发布时间】:2016-06-06 14:03:32
【问题描述】:
我正在 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; }
}
}
}
【问题讨论】: