C# 在ResourceDictionary中创建对定位器的引用

C# 在ResourceDictionary中创建对定位器的引用,c#,wpf,mvvm,service-locator,C#,Wpf,Mvvm,Service Locator,我有一个带有MVVM库的WPF自定义控件库 在字典里我有: <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfCustom

我有一个带有MVVM库的WPF自定义控件库

在字典里我有:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:WpfCustomControlLibrary2"
                    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                    d1p1:Ignorable="d"
                    xmlns:d1p1="http://schemas.openxmlformats.org/markup-compatibility/2006">
<local:ViewModelLocator x:Key="Locator"
                        d:IsDataSource="True" />

在Window.xaml中,我尝试使用该定位器:

<Window x:Class="WPFCustomeControlLibrary.Window"
        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"
        mc:Ignorable="d"
        Title="Window" Height="300" Width="300"
        DataContext="{Binding MainViewModel, Mode=OneWay, Source={StaticResource Locator}}">
<Window.Resources>
    <ResourceDictionary Source="Dictionary.xaml" />
</Window.Resources>
<Grid>

</Grid>

但它仍然说“资源”定位器“无法解析”


定位器是我的ViewModelLocator,其中定义了我的主ViewModel。

将其放入
App.xaml

<Application x:Class="WpfApplication1.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication5" 
             StartupUri="MainWindow.xaml">
  <Application.Resources>
    <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Dictionary.xaml" />
            </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
  </Application.Resources>
</Application>

为什么要将其放在资源字典中?@ThomasV因为WPF自定义控件库中没有其他选项。WPF自定义控件库中没有App.xaml。否。这就是为什么你应该将它添加到实际应用程序的App.xaml中…或者使用我在回答中建议的另一种方法。我正在考虑将每个模块都放在主应用程序中。这是一个问题吗?它与您原来的项目有什么关系?不,这不是问题,但似乎不可能将wpf mvvm项目拆分为不同的程序集。
<Window x:Class="WPFCustomeControlLibrary.Window"
        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"
        mc:Ignorable="d"
        Title="Window" Height="300" Width="300">
    <Window.Resources>
        <ResourceDictionary Source="Dictionary.xaml" />
    </Window.Resources>
    <Grid DataContext="{Binding MainViewModel, Mode=OneWay, Source={StaticResource Locator}}">

    </Grid>
</Window>