gpt4 book ai didi

wpf - MVVM:编辑客户。如何查找具有相同对象的工作区并从另一个工作区创建新工作区

转载 作者:行者123 更新时间:2023-12-02 00:10:49 26 4
gpt4 key购买 nike

就像 this question ,我正在使用 the sample created by Josh Smith 学习 MVVM我想添加一个更新功能。

出现两个问题(在提到的问题中未解决):

  1. 从另一个工作区创建工作区的最佳且简便的方法是什么?
  2. 如何查找是否已存在编辑同一客户的工作区。

最佳答案

这里发生了很多事情。您的问题有两个部分(如果我没有遗漏任何内容)。

  1. 如何将双击操作转发到 ViewModel 中的命令
  2. 如何在此示例中打开“工作区”(在本例中,工作区只是一个选项卡)。

如何双击 ListViewItem,MVVM 样式

有很多方法,但是这个问题总结得很好: 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 的引用,所以当您在一个屏幕中编辑它时,它会在另一个屏幕中更新,而不会发生事件或消息传递(很好!,但可能不够强大)。

组合框有一个小问题,没有自动选择公司/个人的值,但这留给读者作为练习。

作为今天包的一部分,我包含一个功能齐全的演示,无需额外付费。 http://dl.getdropbox.com/u/376992/MvvmDemoApp.zip

希望这有帮助,

安德森

关于wpf - MVVM:编辑客户。如何查找具有相同对象的工作区并从另一个工作区创建新工作区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1579889/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com