【问题标题】:caliburn.micro how to load and bind view for viewmodel runtimecaliburn.micro 如何为视图模型运行时加载和绑定视图
【发布时间】:2011-12-04 18:25:12
【问题描述】:

我正在构建一个需要主题支持的应用程序。所以我想提供视图文件夹运行时间。

public class AppBootstrapper : Bootstrapper<IShell>
{
    CompositionContainer _container;

    /// <summary>
    /// By default, we are configure to use MEF
    /// </summary>
    protected override void Configure()
    {
         //view locator code get views from file and and binding it to viewmodel run time.
    }
}

【问题讨论】:

  • 那么您是否尝试发布几个不同的 DLL,每个 DLL 都有自己的视图副本,并且在运行时您将决定加载哪一个?如果不是,您需要澄清“提供视图文件夹运行时”的含义。
  • @JoeWhite 我只想在 xaml 中提供视图。我不会放入dll。所以当程序启动时,它应该从 xaml 文件中加载所有视图。
  • 您没有提供足够的详细信息。启动后是否需要动态切换主题?或者只是在您的应用程序重新启动时?这将决定您需要走哪条路线。

标签: wpf silverlight xaml mvvm caliburn.micro


【解决方案1】:

在 Caliburn 中,您可以创建自定义的 IConventionManager 或 tweek 实现 (DefaultConventionManager) 以更改框架在运行时查找 View 文件夹的方式。

事实上,视图不一定在 Views 文件夹中,您可以修改此默认行为,因为这只是默认约定。实现此接口的最佳方法是检查默认实现。

【讨论】:

    【解决方案2】:

    更好的调整是使用这种方式(在 Caliburn 中实现,但不是在 Micro 中实现)。 http://caliburnmicro.codeplex.com/discussions/265502

    首先你需要定义一个属性,用来存储用于发现视图的相关数据:

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
    public class ViewAttribute : Attribute
    {
        public object Context { get; set; }
    
        public Type ViewType { get; private set; }
    
        public ViewAttribute(Type viewType)
        {
            ViewType = viewType;
        }
    }
    

    将其附加到您的视图模型。

    [View(typeof(MyView))]
    public class MyViewModel : Screen
    

    然后,您需要将引导程序中的 LocateTypeForModelType 更改为如下内容:

    void Initialize()
    {
        var baseLocate = ViewLocator.LocateTypeForModelType;
    
        ViewLocator.LocateTypeForModelType = (modelType, displayLocation, context) =>
        {
            var attribute = modelType.GetCustomAttributes(typeof(ViewAttribute), false).OfType<ViewAttribute>().Where(x => x.Context == context).FirstOrDefault();
            return attribute != null ? attribute.ViewType : baseLocate(modelType, displayLocation, context);
        };
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-25
      相关资源
      最近更新 更多