0

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?

vargonian
  • 3,064
  • 3
  • 27
  • 36

1 Answers1

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.

erotavlas
  • 4,274
  • 4
  • 45
  • 104
  • My solution so far is to embed all of the resource definitions in the parsed XAML; that's what you're referring to, right? It still surprises me that XamlReader.Parse succeeds, and I add the loaded elements into scene, and it's only later that I get the error about the resource not being found. – vargonian Mar 19 '19 at 01:03
  • @vargonian Sure, but just the resources required by your DataTemplate – erotavlas Mar 19 '19 at 01:17
  • But what if the resource is a custom data type, e.g. a custom type converter defined in the current assembly? I'm getting "Cannot create unknown type" exceptions from that. – vargonian Mar 19 '19 at 01:57
  • Apparently answered my own question with major knocking on wood. I had to change the local namespace in the generated XAML from clr-namespace:MyAssembly to clr-namespace:MyAssembly;assembly=MyAssembly – vargonian Mar 19 '19 at 02:19