Adding an x:Key attribute using Linq to Xml

c#, linq-to-xml, wpf

Solution

    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>

Problem

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?

Original source