基于语句绑定xml时更改数据的最佳方法是什么? 例如,如果“direction”是“N”,那么“North”等等。
这是我的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>
提前谢谢你!
答案 0 :(得分: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;
}