jarmond
jarmond

Reputation: 1382

Adding an x:Key attribute using Linq to Xml

I'm trying to set x:Key in some XAML using Linq to XML so I can add a value converter to the resource dictionary of a data template:

 XNamespace xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
 XNamespace local = "clr-namespace:App,assembly=App";
 XElement dt = new XElement(xmlns + "DataTemplate",
     new XAttribute(XNamespace.Xmlns + "x", "http://schemas.microsoft.com/winfx/2006/xaml"),
     new XAttribute(XNamespace.Xmlns + "local", "clr-namespace:App,assembly=App"),
     new XElement(xmlns + "DataTemplate.Resources",
         new XElement(local + "MyConverter",
             new XAttribute("x:Key", "myConverter"))));

However this raises an exception complaining that ':' is not allowed in attribute names. Using another XNamespace x = "http://schemas.microsoft.com/winfx/2006/xaml" and writing x + "Key" doesn't work either - it gives p3:Key.

Is there some way to include a colon in XAttribute names?

Upvotes: 3

Views: 1697

Answers (1)

Serj-Tm
Serj-Tm

Reputation: 16981

    XNamespace xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
    XNamespace local = "clr-namespace:App,assembly=App";
    XNamespace x = "http://schemas.microsoft.com/winfx/2006/xaml"; 

    XElement dt = new XElement(xmlns + "DataTemplate",
        new XAttribute(XNamespace.Xmlns + "x", "http://schemas.microsoft.com/winfx/2006/xaml"),
        new XAttribute(XNamespace.Xmlns + "local", "clr-namespace:App,assembly=App"),
        new XElement(xmlns + "DataTemplate.Resources",
            new XElement(local + "MyConverter",
                new XAttribute(x + "Key", "myConverter"))));

   Console.WriteLine(dt);

Output:

<DataTemplate xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:App,assembly=App" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
  <DataTemplate.Resources>
    <local:MyConverter x:Key="myConverter" />
  </DataTemplate.Resources>
</DataTemplate>

Upvotes: 4

Related Questions