就像this question一样,我正在使用the sample created by Josh Smith学习MVVM,我想添加更新功能。
出现两个问题(在所提到的问题中未解决):
最佳答案
这里发生了很多事情。您的问题有两个部分(如果我没有什么遗漏的话)。
如何双击MVVM样式的ListViewItem
有很多方法,但是关于SO的这个问题可以很好地总结一下:
Firing a double click event from a WPF ListView item using MVVM
我个人使用了MarlonGrech的附加行为,因此我将向您展示如何做到这一点:
<ListView
AlternationCount="2"
DataContext="{StaticResource CustomerGroups}"
...>
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="acb:CommandBehavior.Event"
Value="MouseDoubleClick" />
<Setter Property="acb:CommandBehavior.Command"
Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}, Path=DataContext.EditCustomerCommand}" />
<Setter Property="acb:CommandBehavior.CommandParameter"
Value="{Binding}" />
</Style>
</ListView.ItemContainerStyle>
</ListView>
这将绑定(bind)到您需要在AllCustomersViewModel中设置的EditCustomerCommand(将是RelayCommand)。
添加新工作区
这个比较棘手。您会注意到MainWindowViewModel有一个AddWorkspace,但是我们确实没有从AllCustomersViewModel引用该ViewModel。
我认为最好的方法(对我而言)将是创建另一个名为“IWorkspaceCommands”的接口(interface),AllCustomersViewModel将使用该接口(interface)创建新的工作区。这主要与先前答复者对Messenger方法的建议形成对比。如果您喜欢Messenger的方法,则可以在此处使用它。
MainWindowViewModel实际上会实现此功能,并在创建AllCustomersViewModel时将其自身传递给它。
public interface IWorkspaceCommands
{
void AddWorkspace(WorkspaceViewModel view);
}
这是该接口(interface)的基本实现。 包括检查该 View 是否已按要求打开(真的很简单!):
#region IWorkspaceCommands Members
public void AddWorkspace(WorkspaceViewModel view)
{
if (!Workspaces.Contains(view))
{
Workspaces.Add(view);
}
SetActiveWorkspace(view);
}
#endregion
最后,这是我在AllCustomersViewModel中告诉您的RelayCommand(以及一些构造函数修改):
IWorkspaceCommands _wsCommands;
public AllCustomersViewModel(CustomerRepository customerRepository, IWorkspaceCommands wsCommands)
{
_wsCommands = wsCommands;
EditCustomerCommand = new RelayCommand(EditCustomer);
...
}
public void EditCustomer(object customer)
{
CustomerViewModel customerVM = customer as CustomerViewModel;
_wsCommands.AddWorkspace(customerVM);
}
就是这样。因为您要处理的是对用于创建AllCustomersViewModel的同一ViewModel的引用,所以当您在一个屏幕中对其进行编辑时,它在没有事件或消息传递的情况下在另一个屏幕中进行更新(很好!但可能不够健壮)。
ComboBox有一个小问题,即无法自动选择公司/人员的值,但这留给读者练习。
作为我今天的软件包的一部分,我的名字是,其中包括一个功能齐全的演示,无需额外付费。
http://dl.getdropbox.com/u/376992/MvvmDemoApp.zip
希望这可以帮助,
安德森
关于wpf - MVVM:编辑客户。如何查找具有相同对象的工作区并从另一个工作区创建新的工作区,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1579889/