我从过去两周开始参加这个wpf。我目前正在开发基于MVVM模式的wpf应用程序。我在Visual C#2010的解决方案中有2个项目。一个是WPF应用程序(比如MSPBoardControl),另一个是类库(比如说ConnectViewComponent)。因此,MSPBoardControl和ConnectViewComponent分别具有view,viewmodel和model类。
我在MSPBoardControl中添加了ConnectViewComponent的引用,我可以在MSPBoardControl的View,Viewmodel和model类中访问ConnectViewComponent的成员变量。我关心的是如何从我的ConnectViewComponent访问MSPBoardControl的成员变量。
MSPBoardControl的ViewModel:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using ConnectViewComponent.Model;
using System.Windows.Input;
using ConnectViewComponent.Commands;
[[[using MSPBoardControl.ViewModel;]]]
namespace ConnectViewComponent.ViewModel
{
public class ConnectViewModel : INotifyPropertyChanged
{
public List<ConnectModel> m_BoardNames;
[[[BoardControlViewModel mBoardVM;]]]
public ConnectViewModel()
{
m_BoardNames = new List<ConnectModel>()
{
new ConnectModel() {Name = "Bavaria", Connection_Status = "Disconnected"},
new ConnectModel() {Name = "Redhook", Connection_Status = "Disconnected"},
};
}
public List<ConnectModel> BoardNames
{
//get set
}
private ConnectModel m_SelectedBoardItem;
public ConnectModel SelectedBoard
{
//get set
}
private ICommand mUpdater;
public ICommand ConnectCommand
{
get
{
if (mUpdater == null)
mUpdater = new DelegateCommand(new Action(SaveExecuted), new Func<bool>(SaveCanExecute));
return mUpdater;
}
set
{
mUpdater = value;
}
}
public bool SaveCanExecute()
{
return true;
}
public void SaveExecuted()
{
if (SelectedBoard.Connection_Status == "Disconnected" && SelectedBoard.Name == "Bavaria")
{
SelectedBoard.Connection_Status = "Connected";
}
else if (SelectedBoard.Connection_Status == "Disconnected" && SelectedBoard.Name == "Redhook")
{
SelectedBoard.Connection_Status = "Connected";
}
}
}
}
我的代码中的[[[ - ]]]表示我无法访问BoardControlViewModel的成员以及USING Namespace.ViewModel。
我无法在ConnectComponent项目中添加BoardControl的引用,因为它会导致循环依赖。我该如何访问它?请帮助!!
答案 0 :(得分:2)
在项目中具有循环依赖关系可能是“代码味道”。有各种方法可以消除这种“气味”。为简单起见,我们假设您有项目A和项目B,它们具有循环依赖性。
将两个项目使用的常用类型分解出来并将它们移动到一个新项目中。让A和B引用C.这应该删除从A到B的依赖关系或相反的依赖关系,甚至是两个依赖关系。
如果A和B具有需要交互的类型,则需要将此交互分离为一组通用的抽象(例如接口或抽象基类)。然后,您应该将这些类型移动到A和B都引用的项目C中,而不进行任何实现。这将允许A和B中的类型进行交互,但仅使用C中的定义。例如,A是主应用程序。它调用C中定义的接口IService
,但在B中实现,并通过IServiceCallback
注册在C中定义的回调IService
。然后,B可以使用IServiceCallback
回调到A,而不知道实现是否在A中。
如果A和B中的类型是强耦合的,则应将A和B合并为一个项目。
答案 1 :(得分:1)
您可以添加某种类型的&#34; Common&#34;库(项目)将包含这些通用类。所以BoardControl和ConnectComponent都可以引用它。
您也可以查看similar question。