Click here to Skip to main content
Licence CPOL
First Posted 20 Jun 2008
Views 24,685
Downloads 227
Bookmarked 12 times

XamlWriter and Bindings Serialization

By AlexDov | 29 Jun 2008
About serialization of Bindings to XAML with the standard MS XamlWriter.
1 vote, 11.1%
1
1 vote, 11.1%
2

3

4
7 votes, 77.8%
5
3.44/5 - 9 votes
μ 3.44, σa 2.74 [?]

Introduction

This article is to show how we can save your dynamically created bindings to XAML by using the standard MS XamlWriter class in a simple and easy manner.

Background

I am one of the developers of a project called FreeSCADA. One of the main parts of this project is the Graphical Designer which has some functionality to save vector graphics in XAML format. In the process of developing, I was faced with a problem. Bindings created from the code (or loaded with a XAML file) were not serialized in XAML format. I was trying to find solutions over the web, but found out only the following article. Unfortunately, this solution isn't suitable for more complex XAML files for some reasons. I did not believe that MS had some special internal solution to this problem, because I saw that the TemplateBinding extension could do such serialization perfectly, but Expression Binding could not. So, I downloaded the MS reference source code for debugging and started studying it. As a result, I found a very simple solution, which I will describe below.

Proposed solution

When I debugged code from MS, I found out that XamlWriter interprets the DependencyProperty value as a Binding. It checks this Binding type for the availability of some registered type converter which can transform this value to the MarkupExtension delivered type. If it is available, then XamlWriter converts this Binding to MarkupExtension and does further serialization.

So, if you want to save your Bindings, you can try the following simple code snippet. Basically, we need a class which looks something like this:

class BindingConvertor : ExpressionConverter
{
    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        if(destinationType==typeof(MarkupExtension))
            return true;
        else return false;
    }
    public override object ConvertTo(ITypeDescriptorContext context, 
                                     System.Globalization.CultureInfo culture, 
                                     object value, Type destinationType)
    {
        if (destinationType == typeof(MarkupExtension))
        {
            BindingExpression bindingExpression = value as BindingExpression;
            if (bindingExpression == null)
                throw new Exception();
            return  bindingExpression.ParentBinding;
        }
        
        return base.ConvertTo(context, culture, value, destinationType);
    }
}

After that, register this class as the type converter for the BindingExpression type. This can be done with the following code:

static class EditorHelper
{
    public static void Register <T, TC>()
    {
        Attribute[] attr = new Attribute[1];
        TypeConverterAttribute vConv = new TypeConverterAttribute(typeof(TC));
        attr[0] = vConv;
        TypeDescriptor.AddAttributes(typeof(T), attr);
    }
    ...
}

And call this function somewhere:

EditorHelper.Register <BindingExpression,BindingConvertor>();

After this, you must switch XamlWriter to the expression saving mode:

StringBuilder outstr=new StringBuilder();
XamlCode.Clear();
//this code need for right XML fomating 
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.OmitXmlDeclaration = true;
XamlDesignerSerializationManager dsm = 
  new XamlDesignerSerializationManager(XmlWriter.Create(outstr, settings));
//this string need for turning on expression saving mode 
dsm.XamlWriterMode = XamlWriterMode.Expression;

XamlWriter.Save(MainPanel, dsm);

That's all you need. A working example can be found in the posted source code zip archive.

P.S.: I'm sorry for some inaccuracies which where there in the first version of this article.

License

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

About the Author

AlexDov

Software Developer

Ukraine Ukraine

Member


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionWorking with ElementName PinmemberHenrique C7:39 31 Oct '11  
GeneralCommand Bindings PinmemberMichaelTR22:00 14 Mar '11  
GeneralItemsControl [modified] PinmemberDydek6:05 30 Mar '10  
GeneralRe: ItemsControl PinmemberAlexDov19:42 30 Mar '10  
GeneralRe: ItemsControl PinmemberCD_Fighter1:57 30 Sep '11  
QuestionHow to skip serialization of individual child controls? PinmemberMember 18164264:30 5 Oct '09  
QuestionSupport for StaticResource ? Pinmemberxradux20011:40 19 Jun '09  
GeneralAny UnRegister PinmemberAtul C8:12 8 Apr '09  
GeneralRe: Any UnRegister Pinmemberspastik4:33 3 Sep '10  
QuestionAny solution for serializing StaticResource? PinmemberAmzSales13:09 10 Nov '08  
AnswerRe: Any solution for serializing StaticResource? PinmemberAlexDov20:10 10 Nov '08  
GeneralRe: Any solution for serializing StaticResource? PinmemberAmzSales20:40 10 Nov '08  
GeneralRe: Any solution for serializing StaticResource? PinmemberAlexDov22:56 10 Nov '08  
GeneralRe: Any solution for serializing StaticResource? PinmemberAmzSales5:05 11 Nov '08  
AnswerRe: Any solution for serializing StaticResource? PinmemberAlexDov2:24 14 Nov '08  
GeneralRe: Any solution for serializing StaticResource? Pinmemberc0desmurf12:45 11 Nov '09  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120209.1 | Last Updated 29 Jun 2008
Article Copyright 2008 by AlexDov
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid