DataTemplate + MVVM

Chr*_*nko 5 wpf datatemplate mvvm

我正在使用MVVM,每个View都映射到具有约定的ViewModel.IE MyApp.Views.MainWindowView MyApp.ViewModels.MainWindowViewModel

有没有办法删除DataTemplate并在C#中执行?有某种循环?

<DataTemplate DataType="{x:Type vm:MainWindowViewModel}">
    <vw:MainWindowView />
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)

Tho*_*que 6

So basically, you need to create data templates programmatically... That's not very straightforward, but I think you can achieve that with the FrameworkElementFactory class :

public void AddDataTemplateForView(Type viewType)
{
    string viewModelTypeName = viewType.FullName + "Model";
    Type viewModelType = Assembly.GetExecutingAssembly().GetType(viewModelTypeName);

    DataTemplate template = new DataTemplate
    {
        DataType = viewModelType,
        VisualTree = new FrameworkElementFactory(viewType)
    };

    this.Resources.Add(viewModelType, template);
}
Run Code Online (Sandbox Code Playgroud)

I didn't test it, so a few adjustments might be necessary... For instance I'm not sure what the type of the resource key should be, since it is usually set implicitly when you set the DataType in XAML


Chr*_*nko 6

谢谢托马斯,使用你的代码我做到了这一点.

添加资源时需要使用DataTemplateKey:D

    private void AddAllResources()
    {
        Type[] viewModelTypes = Assembly.GetAssembly(typeof(MainWindowViewModel)).GetTypes()
            .Where(t => t.Namespace == "MyApp.ViewModels" && t.Name.EndsWith("ViewModel")).ToArray();

        string viewName = null;
        string viewFullName = null;

        foreach (var vmt in viewModelTypes)
        {
            viewName = vmt.Name.Replace("ViewModel", "View");
            viewFullName = String.Format("MyApp.Views.{0}, MyApp", viewName);

            DataTemplate template = new DataTemplate
            {
                DataType = vmt,
                VisualTree = new FrameworkElementFactory(Type.GetType(viewFullName, true))
            };

            this.Resources.Add(new DataTemplateKey(vmt), template);
        }
    }
Run Code Online (Sandbox Code Playgroud)