【问题标题】:XAML Binding data of an XML attribute and displaying its valueXAML 绑定 XML 属性的数据并显示其值
【发布时间】:2015-05-15 05:56:36
【问题描述】:

我正在为 Windows Phone 制作简单的 RSS 阅读器,它使用 XML Serializer 读取 XML 文件并显示项目列表。我有 Rss.css 文件,其中我有项目类(在片段下方):

public class Item
{
    [XmlElement("title")]
    public string Title { get; set; }

    [XmlElement("link")]
    public string Link { get; set; }
}

我在 XAML 文件中绑定数据并显示例如像这样的标题字段:

<ListView Grid.Row="1" ItemsSource="{Binding Rss.Channel.Items}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                   <ColumnDefinition Width="150" />
                   <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <TextBlock Text="{Binding Title}"/>

等等,它工作正常。现在,假设在 XML 标题中有一个属性,例如短=“真”。 如何绑定和显示这个属性?

我尝试在 Item 类下创建另一个类:

public class Title
{
    [XmlAttribute("short")]
    public string Short { get; set; }

}

并像这样简单地绑定属性:

<TextBlock Text="{Binding Title.Short}"/>

但它不起作用。我可以以某种方式在 XAML 中“访问”它,还是应该更改 .cs 文件中的某些内容?

PS。给定的示例是我的问题的一个较短的替代方案,因此它不一定非常合乎逻辑。

【问题讨论】:

  • 您应该能够通过使用 XPath 绑定来实现这一点。像这样的东西:&lt;TextBlock Text="{Binding XPath=@Short}"/&gt;
  • 我猜你的意思是 {Binding Path=@Short},因为编译器说没有用于绑定的“XPath”这样的属性,但它仍然不起作用。
  • 通过一些调试,您应该能够看到这个问题的一半。问题要么是 XML 没有正确反序列化(Shortnull),要么是绑定工作不正常(Short 有一个值,但它没有绑定到 UI)。是哪个?
  • 当我使用 行运行应用程序时,调试输出中出现此错误:错误:BindingExpression 路径错误:在“字符串”上找不到“短”属性。
  • 如果你绑定到Title.Short 并且上下文是Item,那么它会神奇地从哪里得到ShortTitlestring - 你的错误指出了这一点。

标签: c# xaml data-binding rss xmlserializer


【解决方案1】:

您正在绑定到不存在的东西 - Title 在您的模型中是 string。您应该更改它,以便反序列化可以同时为您提供标题和属性:

public class Item
{
    [XmlElement("title")]
    public Title Title { get; set; }

    [XmlElement("link")]
    public string Link { get; set; }
}

public class Title
{
    [XmlAttribute("short")]
    public string Short { get; set; }

    [XmlText]
    public string Value { get; set; }
}

然后您当前的Title 绑定更改为Title.Value 并且您的Title.Short 绑定应该可以工作。

【讨论】:

  • 非常感谢,它确实有效,但是我需要它来从这个标记中提取 url:&lt;media:thumbnail url="http://12345.jpg"/&gt;,奇怪的是在这种情况下它不起作用。结肠可能是问题吗?在项目中我有 [XmlElement(media:thumbnail)] public MediaThumbnail MediaThumbnail { get; set; } 和下面我有带有 url 属性的 MediaThumbnail 类。
  • 不,media 是命名空间前缀。在某个地方,您将拥有xmlns:media="http://example.com/ 属性。 XmlElement 属性应该包括这个,例如[XmlElement("thumbnail", Namespace = "http://example.com/")]
猜你喜欢
  • 1970-01-01
  • 2014-08-11
  • 1970-01-01
  • 2015-04-24
  • 1970-01-01
  • 1970-01-01
  • 2010-10-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多