How to reference existing Resources from a XamlReader.Parse(xmlFragment) call

徘徊边缘 提交于 2019-12-11 23:25:16

问题


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>

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.

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


回答1:


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.



来源:https://stackoverflow.com/questions/55231130/how-to-reference-existing-resources-from-a-xamlreader-parsexmlfragment-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!