简体   繁体   English

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

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

I am making simple RSS reader for Windows Phone which reads an XML file using XML Serializer and displays the list of items. 我正在为Windows Phone制作简单的RSS阅读器,该阅读器使用XML序列化器读取XML文件并显示项目列表。 I have Rss.css file and amongst others I have item class (below fragment): 我有Rss.css文件,除其他外,我还有项目类(下面的片段):

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

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

And I am binding data in XAML files and displaying eg title field like this: 我将数据绑定到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}"/>

etc., and it's working fine. 等,并且工作正常。 Now, let's say that in the XML title has an attribute, eg short="true". 现在,假设XML标题中有一个属性,例如short =“ true”。 How do I bind and display this attribute? 如何绑定和显示此属性?

I tried to create another class under Item class: 我试图在Item类下创建另一个类:

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

}

and simply bind the attribute like this: 并像这样简单地绑定属性:

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

but it's not working. 但它不起作用。 Can I "reach" it in XAML somehow or should I change something in the .cs file? 我可以以某种方式在XAML中“到达”它还是应该更改.cs文件中的内容?

PS. PS。 The given example is a shorter alternative to my problem therefore it is not necessarily very logical. 给定的示例是我的问题的较短替代方案,因此它不一定是很合逻辑的。

You're binding to something that doesn't exist - Title is a string in your model. 您将绑定到不存在的内容- Title是模型中的string You should change this so the deserialization can give you both the title and the attribute: 您应该更改此设置,以便反序列化可以为您提供标题和属性:

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

Then your current Title binding changes to Title.Value and your Title.Short binding should work. 然后,您当前的Title绑定将更改为Title.Value并且Title.Short绑定应该起作用。

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

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