繁体   English   中英

XAML绑定XML属性的数据并显示其值

[英]XAML Binding data of an XML attribute and displaying its value

我正在为Windows Phone制作简单的RSS阅读器,该阅读器使用XML序列化器读取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标题中有一个属性,例如short =“ true”。 如何绑定和显示此属性?

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

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

}

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

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

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

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

您将绑定到不存在的内容- 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绑定应该起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM