我想在子窗口中使用View Model Locator。 问题是这不起作用:
<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}}>
我收到错误: 找不到名称/密钥定位器的资源
答案 0 :(得分:1)
使用定位器模式将子窗口绑定到静态视图模型没有任何技巧。我的猜测是你的DataContext错了。
检查: 确保在定位器类中定义了“AddAlert”属性。类似的东西:
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;
}
}
当然,请确保您的视图模型定位器在App.xaml文件中实例化:
<vm:MyModelLocator xmlns:vm="clr-namespace:MyAppNamespace" x:Key="Locator" />
答案 1 :(得分:1)
好的,它无法工作的原因是我的childWindow是在IApplicationService的ctor中创建的。
此popupService在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>
显然,视图是在之前应用资源创建的!