Skip to main content
Home Forums Silverlight Programming Programming with .NET - General How do I Bind an XElement Attribute in CodeBehind
5 replies. Latest Post by msalsbery on November 5, 2009.
(0)
nbruckel...
Member
9 points
25 Posts
11-04-2009 11:26 AM |
I have the following XElement document and I am trying to bind the elements and attributes to a datagrid from codebehind. I need to do it from codebehind so I can build my datagrid dynamically. The element is binding but the attributes are not binding correctly. Does anyone know how to get the attributes to display.
Here is my XElement:XElement element = new XElement("Root", new XElement("Role", new XAttribute("CanEditUsers",false), new XAttribute("CanViewUsers",true), "Administrator"));
IEnumerable
This is what the output looks like: (The columns are correct but the values for the attributes are not)
msalsbery
Contributor
2066 points
379 Posts
11-04-2009 3:12 PM |
nbruckelmyer:The columns are correct but the values for the attributes are not
You're setting the same binding on all the columns, so you get the same value in all the columns :)
You could use a converter on the attribute column bindings, passing the attribute name as the converter parameter. An example is shown in the "Answers" section here. (thank you to Bryant for saving me from typing up an example :))
11-05-2009 9:56 AM |
How can I do this from codebehind?
Jeremy L...
330 points
59 Posts
11-05-2009 10:11 AM |
I've found it's a lot easier to define a class that represents the parsed XML values. Use LINQ to XML to load the entity/class from the XML, then bind to the class instead of trying to bind to the Xml fragments.
11-05-2009 11:22 AM |
Do you know if its possible to do what I am trying. I can't create a class based on the xml cause it's a dynamic data.
11-05-2009 12:52 PM |
nbruckelmyer:How can I do this from codebehind?
foreach (var a in e.Attributes()) { Binding attbinding = new Binding(); attbinding.Converter = new XAttributeConverter(); attbinding.ConverterParameter = a.Name.LocalName; this.dgTest.Columns.Add( new DataGridTextColumn { Header = a.Name.LocalName, Binding = attbinding }); }