Click here to Skip to main content
15,891,431 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all



I'm trying to get a DatatTemplate from a ResourceDictionary in code. The problem is when I'm trying to save it to string I get all the Binding location to be either empty or null.

Here is my piece of code

ResourceDictionary dictionary = new ResourceDictionary();
dictionary.Source = new Uri("WpfApplication1;component/Dict.xaml", UriKind.RelativeOrAbsolute);
DataTemplate template = (DataTemplate) dictionary["helloTextBox"];
string save = XamlWriter.Save(template.LoadContent());



I'd be happy for any insight.

Thanks
Posted

1 solution

It turns out I need to register a binding converter for BindingExpression in TypeConverter in order for the serialize to work on bindings as by default they are not serialized.

Needs to add this class as the ExpressionConverter


public class BindingConverter : ExpressionConverter
{
public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, Type destinationType)
{
return true;
}

public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(MarkupExtension))
{
BindingExpression bindingExpression = value as BindingExpression;
if (bindingExpression == null)
{
throw new FormatException("Expected binding, but didn't get one");
}
return bindingExpression.ParentBinding;
}
return base.ConvertTo(context, culture, value, destinationType);
}
}


and then use this mehtod to register where I do the XamlWriter.Save part


private void Register()
{
Attribute[] attr = new Attribute[1];
TypeConverterAttribute vConv = new TypeConverterAttribute(typeof(BindingConverter));
attr[0] = vConv;
TypeDescriptor.AddAttributes(typeof(BindingExpression), attr);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900