如何通过XamlReader.Parse(xmlFragment)调用引用现有资源 [英] How to reference existing Resources from a XamlReader.Parse(xmlFragment) call

查看:199
本文介绍了如何通过XamlReader.Parse(xmlFragment)调用引用现有资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一种情况下,我正在使用XamlReader.Parse(xamlString)创建自定义DataTemplate,其中xamlString是包含DataTemplate的片段:

I have a situation in which I'm creating a custom DataTemplate using XamlReader.Parse(xamlString), where xamlString is the fragment which contains the DataTemplate:

<DataTemplate xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <StackPanel Visibility="{Binding MyBinding, Converter={StaticResource boolToVisibilityConverter}}">
        ...
    </StackPanel>
</DataTemplate>

如您所见,此DataTemplate引用了静态资源(BooleanToVisibilityConverter)。对XamlReader.Parse的调用无一例外地完成,我将其结果(一个DataTemplate对象)分配给场景层次结构中的一个对象(在本例中为GridViewColumn.CellTemplate)。但是由于某些原因,在调用MainWindow.Show()时出现异常:

As you can see, this DataTemplate has a reference to a static resource (the BooleanToVisibilityConverter). The call to XamlReader.Parse completes without exception, and I assign its result (a DataTemplate object) to an object in the scene hierarchy (in this case, a GridViewColumn.CellTemplate). But for some reason in the call to MainWindow.Show() I get the exception:

System.Windows.Markup.XamlParseException: ''Provide value on 'System.Windows.Markup.StaticResourceHolder' threw an exception.' Line number 'x' and line position 'y'.'

Inner Exception:
Exception: Cannot find resource named 'boolToVisibilityConverter'. Resource names are case sensitive.

为什么加载的XAML片段不能引用页面中的现有资源?

Why can't the loaded XAML fragment reference an existing resource in the page?

推荐答案

最初创建XAML片段时,我认为它不知道要放置其的父容器的任何信息,包括静态容器。父级中定义的资源。尝试使用DataTemplate.Resources引用DataTemplate内部的boolToVisibilityConverter。

When the XAML fragment gets created initially I don't think it knows anything about the parent container that your going to place it in, including the static resources defined in the parent. Try to reference the boolToVisibilityConverter inside the DataTemplate using DataTemplate.Resources instead.

这篇关于如何通过XamlReader.Parse(xmlFragment)调用引用现有资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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