3

我正在尝试使用 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名称中包含冒号吗?

4

1 回答 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);

输出:

<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>
于 2012-07-11T08:51:42.670 回答