如何在XElement和ListBox之间进行绑定?

时间:2011-09-26 14:13:33

标签: silverlight binding

我持有XElement - 显示为

<Root>     
     <child1>1</child1>     
     <child2>2</child2>    
     <child3>3</child3>   
     <child4>4</child4>  
</Root> 

我想在某些ListBox上显示此Element +值。

所以我定义了这个xaml - 但没有任何作用...... 我怎么能这样做?

<ListBox ItemsSource="{Binding XMLProperty}" >
     <ListBox.ItemTemplate>
          <DataTemplate>
               <Grid>
                  <Grid.ColumnDefinitions>
                      <ColumnDefinition Width="*.5"   />
                      <ColumnDefinition Width="*.5"   />
                  </Grid.ColumnDefinitions>

                  <TextBlock Grid.Column="0" Text="{Binding Element}" />
                  <TextBlock Grid.Column="1" Text="{Binding Value  }" />
               </Grid>
            </DataTemplate>
      </ListBox.ItemTemplate>
   </ListBox>

1 个答案:

答案 0 :(得分:1)

XElement没有用于列出其子元素的IEnumerable接口。为了枚举您需要调用Elements()方法的元素。为了帮助您创建一个价值转换器: -

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

现在你的Xaml应该是这样的: -

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