2

我想在子窗口中使用视图模型定位器。问题是这不起作用:

<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}}>

我收到错误: 找不到具有名称/密钥定位器的资源

4

2 回答 2

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" />
于 2011-08-17T12:28:41.307 回答
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>

显然,视图是在应用程序资源之前创建的!

于 2011-10-10T14:41:45.510 回答