caliburn.micro如何为viewmodel运行时加载和绑定视图

时间:2011-10-10 19:04:31

标签: wpf silverlight xaml mvvm caliburn.micro

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

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

2 个答案:

答案 0 :(得分:4)

更好的调整是使用这种方式(在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);
    };
}

答案 1 :(得分:3)

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

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

相关问题