I hold XElement - that appear as this
<Root>
<child1>1</child1>
<child2>2</child2>
<child3>3</child3>
<child4>4</child4>
</Root>
I want to show this Element + value on some ListBox.
So i define this xaml - but nothing work ... How can i do it right ?
<ListBox ItemsSource="{Binding XMLProperty}" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*.5" />
<ColumnDefinition Width="*.5" />
</Grid.ColumnDefinitions>
开发者_JAVA百科 <TextBlock Grid.Column="0" Text="{Binding Element}" />
<TextBlock Grid.Column="1" Text="{Binding Value }" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
An XElement does not have a IEnumerable
interface through which to list its child elements. In order to enumerate the elements you need to call the Elements()
method. To assist you could create a value converter:-
public class ElementConverter : IValueConverter
{
public override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
XElement source = value as XElement;
if (source != null)
{
return source.Elements();
}
return null;
}
public override object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Now your Xaml should look like:-
<Grid.Resources>
<local:ElementConverter x:Key="conv" />
</Grid.Resources>
...
<ListBox ItemsSource="{Binding XMLProperty, Converter={StaticResources conv}}" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Name.LocalName}" />
<TextBlock Grid.Column="1" Text="{Binding Value }" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
精彩评论