【问题标题】:Change data when binding based on a statement基于语句绑定时更改数据
【发布时间】:2014-02-16 18:00:48
【问题描述】:

在基于语句绑定 xml 时更改数据的最佳方法是什么? 例如,如果“方向”是“N”,那么“北”等等。

这是我的 c#:

XElement Xmlwater = XElement.Parse(e.Result);

listBox3.ItemsSource = from WindInfo in Xmlwater.Descendants("Wind")
        select new WindDirection
{
       Direction = WindDirection.Element("direction").Value,
};

这是 XML:

<Wind>
   <direction>N</direction>
</Wind>

提前谢谢你!

【问题讨论】:

    标签: c# xml windows-phone-8 binding


    【解决方案1】:

    有两种可能的方法:

    1.您可以修改 LINQ 查询以进行转换:

    listBox3.ItemsSource = from WindInfo in Xmlwater.Descendants("Wind")
        select new WindDirection
        {
            Direction = MapValue(WindDirection.Element("direction").Value),
        };
    

    2.您可以实现IValueConverter:

    public class WindDirectionConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, 
                              object parameter, CultureInfo culture)
        {
            return MapValue(value.ToString());
        }
    
        public object ConvertBack(object value, Type targetType, 
                                  object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    您将此转换器添加到您的绑定表达式中:

    <Page.Resources>
        <conv:WindDirectionConverter" x:Key="WindDirectionConverter" />
    </Page.Resources>
    
    <TextBlock Text="{Binding Direction, 
                      Converter={StaticResource WindDirectionConverter}}" />
    

    在这两种情况下,我都假设您有一个 MapValue 函数为您进行值映射:

    public string MapValue(string original)
    {
        if (original == "N")
        {
            return "North";
        }
        // other conversions
        return original;
    }
    

    【讨论】:

    • 非常感谢。这真的很有帮助!
    猜你喜欢
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多