使用Linq向Xml添加x:Key属性

时间:2012-07-11 08:47:32

标签: c# wpf linq-to-xml

我正在尝试使用Linq to XML在一些XAML中设置x:Key,这样我就可以将值转换器添加到数据模板的资源字典中:

 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"))));

然而,这引发了一个例外,抱怨在属性名称中不允许使用':'。使用其他XNamespace x = "http://schemas.microsoft.com/winfx/2006/xaml"并撰写x + "Key"也不起作用 - 它会p3:Key

是否有某种方法可以在XAttribute名称中包含冒号?

1 个答案:

答案 0 :(得分: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);

输出:

<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>