【问题标题】:Use MVVM Light View Model Locator with Child Window in Silverlight 4在 Silverlight 4 中使用带有子窗口的 MVVM Light View Model Locator
【发布时间】:2011-10-28 18:57:43
【问题描述】:

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

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

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

【问题讨论】:

  • 你最后错过了“”。我修好了,试试看:DataContext="{Binding AddAlert, Source={StaticResource Locator}}">

标签: silverlight-4.0 mvvm-light childwindow viewmodellocator


【解决方案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" />

【讨论】:

    【解决方案2】:

    好吧,它不起作用的原因是我的 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-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多