3

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?

1 Answer 1

4
    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>
Sign up to request clarification or add additional context in comments.

2 Comments

As noted in the question, that doesn't work. It gives, in this case, p0:Key="myConverter".
You're right, it does work, thanks. Turns out I had a naming mismatch between the xmlns:local and local.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.