c# - 使用 XamlReader 创建的 DataTemplate 无法找到 StaticResources

标签 c# wpf xaml datatemplate

此代码无法正确加载,而在 XAML 中声明相同的 DataTemplate 则可以正常工作。

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    this.Resources.Add("a", "Hello");
    DataTemplate t = GetObject("<DataTemplate><Label Content=\"{Binding Source={StaticResource a}}\"/></DataTemplate>") as DataTemplate;
    list.ItemTemplate = t;
    list.Items.Add(77);
}

public static Object GetObject(string xaml)
{
    MemoryStream sr = null;
    ParserContext pc = new ParserContext();
    sr = new MemoryStream(Encoding.ASCII.GetBytes(xaml));
    pc.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
    pc.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
    return XamlReader.Load(sr, pc);
}

我需要在代码中执行此操作。怎么办?

最佳答案

我认为 StaticResource 需要在加载时解析,因为它不在上下文中,所以它会失败。 DynamicResource 可以工作,因为它可以等到查询后提供值,但 DynamicResource 不能用作 Binding 的源.

如果您的情况允许,您可以将资源添加到 DataTemplate 中,如下所示

DataTemplate t = GetObject(@"
    <DataTemplate>
        <DataTemplate.Resources>
            <sys:String x:Key=""a"">Hello</sys:String>
        </DataTemplate.Resources>
        <Label Content=""{Binding Source={StaticResource a}}""/>
    </DataTemplate>") as DataTemplate;
list.ItemTemplate = t;

您还需要添加 Xmlns 字典

pc.XmlnsDictionary.Add("sys", "clr-namespace:System;assembly=mscorlib");

关于c# - 使用 XamlReader 创建的 DataTemplate 无法找到 StaticResources,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7173302/

相关文章:

c# - 如何从带有变量的 Access 数据库运行 C# 中的 Select 语句?

C# 如何处理多种消息类型?

c# - MySql 数据库的连接字符串

WPF 在单独的网格之间共享列宽

c# - 在WPF TreeView (MVVM)中取消选择所选项目

wpf - 从子usercontrol datagrid行动态加载父用户控件表单

c# - 开发非常基本的 Windows 8.1 应用程序。如何从后面的 xaml 代码执行验证

wpf - 在 XAML 中绑定(bind)到 AssemblyVersion(用于帮助/关于对话框)

wpf - 为什么要添加 x :Name attribute to a user control cause a compilation error?

c# - 所有者绘制的列表框未绘制先前选择的项目