在WPF,C#中以编程方式将DataTemplate添加到资源中 [英] Add DataTemplate into Resources Programatically in WPF, C#

查看:89
本文介绍了在WPF,C#中以编程方式将DataTemplate添加到资源中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我有以下WPF代码:

Hi guys,

I have a WPF code as below :

<UserControl x:Class="Sample"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:view="Sample.view"
             xmlns:viewModel="Sample.viewModel"
             Width="auto" VerticalAlignment="Top">





<UserControl.Resources>
    <DataTemplate DataType="{x:Type viewModel:SelectionViewModel}">
        <view:Transaction />
    </DataTemplate>
    <DataTemplate DataType="{x:Type viewModel:ConfigurationViewModel}">
        <view:Configuration />
    </DataTemplate>
</UserControl.Resources>


</UserControl>


我想在后面的代码中以编程方式将那些DataTemplates添加到资源中.

我的查询是如何以编程方式创建数据模板,以及如何在后面的代码中将其添加到资源中?
谢谢:)


</UserControl>


I would like to add Those DataTemplates into Resources Programatically in Code behind.

My query is how to create data template programatically and how to add it into resoruces in code behind?

Thanks :)

推荐答案

根据SDK,建议以编程方式创建模板的方法是使用XamlReader.Load()方法从字符串或内存流中加载XAML. .相信我,这是最简单的方法.动态地构建必要的xaml字符串,然后将其加载非常容易.

要将模板添加到您的资源中,您可能应该创建一个包含模板的ResourceDictionary,使用XamlReader.Load加载xaml,然后像这样合并字典.

According to the SDK, the recommended way to programmatically create a template is to load XAML from a string or a memory stream using the XamlReader.Load() method. Believe me, that''s the easiest way. It''s very easy to build the necessary xaml string dynamically, and then load it.

To add the template to your Resources, you probably should create a ResourceDictionary with your template in it, use XamlReader.Load to load the xaml, and then merge the dictionary, like so.

this.Resources.MergedDictionaries.Add(myResourceDictionary); 


这篇关于在WPF,C#中以编程方式将DataTemplate添加到资源中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆