Reputation: 131
I have a WPF Custom Control Library with MVVM Libraries.
In Dictionary I have:
<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" />
And in Window.xaml I try to use that Locator:
<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>
But it still says 'The resource 'Locator' could not be resolved'.
Locator is my ViewModelLocator where my MainViewModel is defined.
Upvotes: 0
Views: 317
Reputation: 169340
Put it in 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>
The resource cannot be defined in the window since it needs to be resolved before the DataContext
is set.
The other option would be to set the DataContext
of the Grid
instead of the Window
:
<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>
Upvotes: 1