Use MVVM Light View Model Locator with Child Window in Silverlight 4
I want to use the View 开发者_运维知识库Model Locator in a Child Window. Problem is this don't work:
<controls:ChildWindow x:Class="Views.PopupViews.AddAlert"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr namespace:System.Windows.Controls;assembly=System.Windows.Controls"
DataContext="{Binding AddAlert, Source={StaticResource Locator}}>
I get the error: Cannot find a Resource with the Name/Key Locator
There is no trick to binding a child window to a static view model using the locator pattern. My guess is your DataContext is wrong.
Check: Make sure you have an "AddAlert" property defined in your locator class. Something like:
private static AddAlertViewModel _AddAlertViewModel;
/// <summary>
/// Gets the ViewModelPropertyName property.
/// </summary>
public static AddAlertViewModel AddAlertViewModelStatic
{
get
{
if (_AddAlertViewModel == null)
{
CreateAddAlertViewModel();
}
return _AddAlertViewModel;
}
}
/// <summary>
/// THIS PROPERTY IS WHAT YOU NEED TO REFERENCE IN YOUR XAML
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This non-static member is needed for data binding purposes.")]
public AddAlertViewModel AddAlert
{
get
{
return AddAlertViewModelStatic;
}
}
And of course make sure your view model locator is instantiated in your App.xaml file:
<vm:MyModelLocator xmlns:vm="clr-namespace:MyAppNamespace" x:Key="Locator" />
Ok the reason why it don't works is my childWindow is created inside the ctor of an IApplicationService.
This popupService is declared in the App.xaml:
<Application.Resources>
<ResourceDictionary>
<vm:ViewModelLocator xmlns:vm="clr-namespace:Client.ViewModel" x:Key="Locator" />
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Assets/Styles.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
<Application.ApplicationLifetimeObjects>
<popup:myPopupService/>
</Application.ApplicationLifetimeObjects>
Apparently, the view was created before the app resources !
精彩评论