There’s quite a few questions about loading XAML at runtime here,
but as far I can tell this is not a duplicate.
I’m loading XAML into a control at runtime:
<ContentControl Content="{Binding Layout.View, Converter={StaticResource StringToXamlConverter}}"/>
The converter is rather simple:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string xaml;
if (value != null)
{
xaml = value.ToString();
}
else
{
xaml = Settings.Default.DefaultLayoutView;
}
var root = XamlReader.Parse(xaml);
return root;
}
Now, in the XAML that is being loaded, I need to make use of ValueConverters.
The converters are defined as resources of the Window in to which the XAML is loaded. For example:
<c:BooleanToVisibilityValueConverter x:Key="BooleanToVisibilityConverter"/>
Of course, the XamlReader.Parse() method throws an exception if I try to use this resource as at the time of reading it is not available.
Visibility="{Binding Layout.TextItem1.IsEnabled, Converter={StaticResource BooleanToVisibilityConverter}}"
Is there a way to get around this?
Perhaps a way to tell the XamlReader to ignore this?
Or an alternative to ValueConverters that might work in this situation?
Please note, using a DynamicResource does not work either. They cannot be used for ValueConverters.
UPDATED
OK, You are right, dynamic resources will not work. I have come up with two solutions, and the best part is, I have tested and both will actually work.
Choice 1: Define the static resource in the application resources app.xaml
Choice 2: Do not use a static resource for the converter, just create the converter in the xaml. Sorry for not going off the xaml you were using, but you’ll get the idea: