【问题标题】:How to make binding between XElement and ListBox ?如何在 XElement 和 ListBox 之间进行绑定?
【发布时间】:2011-09-26 14:13:32
【问题描述】:

我持有 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>

【问题讨论】:

  • “显示此元素”是什么意思?你的意思是元素名称吗?还有你要绑定的 XMLProperty 是什么?

标签: silverlight binding


【解决方案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>

【讨论】:

    猜你喜欢
    • 2016-02-12
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多