我必须在一个独立的用户控件库中创建一个WPF用户控件。我想用MVVM灯。问题是,SimpleIOC通常设置在主应用程序中,并通过app.xaml作为资源添加到主应用程序中。
如何最好地解决这个问题,以便引用的用户控件库能够访问SimpleIOC容器?我最好在哪里注册用户控件的ViewModel?
我发现下面的线程似乎是相同的问题,但在答案帖子中提供的链接中不再有关于解决方案的任何信息。How can MVVM Light be used in a WPF User Control Library project?
发布于 2018-08-06 11:58:57
如果独立类库中的视图依赖于视图模型定位器,而视图模型定位器又依赖于视图模型类,则可以将ViewModelLocator类定义为视图模型项目中的单例,并从用户控制库和WPF应用程序本身引用该项目:

ViewModels/ViewModelLocator.cs:
public sealed class ViewModelLocator
{
private static readonly ViewModelLocator _instance = new ViewModelLocator();
private ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<MainViewModel>();
}
public static ViewModelLocator Instance => _instance;
public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
}Views/UserControl1.xaml:
<UserControl x:Class="Views.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:viewModels="clr-namespace:ViewModels;assembly=ViewModels"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
DataContext="{Binding Main, Source={x:Static viewModels:ViewModelLocator.Instance}}">
<Grid>
</Grid>
</UserControl>WpfApp4/MainWindow.xaml:
<Window x:Class="WpfApp4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:views="clr-namespace:Views;assembly=Views"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<views:UserControl1 />
</Grid>
</Window>发布于 2018-08-06 09:56:17
现在还不清楚你在这件事的哪一部分有问题。库中的视图模型可以与任何其他视图模型注册的方式相同:
SimpleIoc.Default.Register<MainViewModel>();
SimpleIoc.Default.Register<YourClassLibrary.YourClassLibViewModel>();
... etc ...如果类库中有需要包含在主应用程序资源字典(即DataTemplates等)中的对象,那么将它们放入ResourceDictionary中,就像通常在App.xaml中所做的那样.
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:YourClassLibrary">
<DataTemplate DataType="{x:Type local:YourClassLibViewModel}">
<local:YourClassLibUserControl />
</DataTemplate>
</ResourceDictionary>然后,...and将其添加到主应用程序的ResourceDictionary的MergedDictionaries列表中:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/YourClasssLibrary;component/YourResourceDictionary.xaml" />
</ResourceDictionary.MergedDictionaries>
<vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" xmlns:vm="clr-namespace:YourMainApp.ViewModel" />
</ResourceDictionary>
</Application.Resources>https://stackoverflow.com/questions/51702856
复制相似问题