2017-08-17 43 views
0

我有一個帶有MVVM庫的WPF自定義控件庫。在ResourceDictionary中創建對Locator的引用

在字典我有:

<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,其中定義了我的MainViewModel。

+0

你爲什麼把它在一個資源字典擺在首位? –

+0

@ThomasV因爲在WPF自定義控件庫中沒有其他選項。 – user7998549

回答

1

放入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> 

的資源不能在窗口,因爲它需要解決被設置DataContext之前定義。

的另一個選項是設置Grid,而不是WindowDataContext

<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> 
+0

WPF自定義控件庫中沒有App.xaml。 – user7998549

+0

不,這就是爲什麼你應該將它添加到實際應用程序的App.xaml中......或者按照我在答案中提出的方法使用另一種方法。 – mm8

+0

我正在考慮將每個模塊放在主應用程序中。 – user7998549

相關問題