Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 365
jarmond Avatar asked Jan 27 '26 14:01

jarmond


1 Answers

    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>
like image 137
Serj-Tm Avatar answered Jan 29 '26 04:01

Serj-Tm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!