以编程方式将DataTemplate添加到资源字典

时间:2019-01-15 18:02:00

标签: c# wpf datatemplate

<Window x:Class="App1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:cust="clr-namespace:App1.Customers"
    Title="Customers"
    Height="525"
    Width="525">

<Window.Resources>
    <DataTemplate DataType="{x:Type cust:CustomerViewModel}">
        <cust:CustomerView />
    </DataTemplate>
</Window.Resources>
<Grid x:Name="MainContent">
    <ContentControl Content="{Binding CurrentViewModel}" />
</Grid>
</Window>

我已经在xaml中声明了数据模板。随着时间的流逝,主窗口可能需要了解20个视图模型和视图。我宁愿将数据模板添加到资源字典的责任转移到其他地方。如何在C#中实现以上目标?只是将数据模板添加到资源字典中的那一点

1 个答案:

答案 0 :(得分:0)

您可以使用XamlReader.Load方法动态创建模板:

ParserContext parserContext = new ParserContext();
parserContext.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
parserContext.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
parserContext.XmlnsDictionary.Add("cust", "clr-namespace:App1.Customers;assembly=" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
const string Xaml = "<DataTemplate>" +
                        "<cust:CustomerView />" +
                     "</DataTemplate>";

Resources.Add(new DataTemplateKey(typeof(CustomerViewModel)), 
              XamlReader.Parse(Xaml, parserContext) as DataTemplate);