【问题标题】:Databinding listbox to a list<string[]>将列表框数据绑定到列表<string[]>
【发布时间】:2012-09-06 15:20:10
【问题描述】:

我很难通过 XAML 将我的 List 类型的属性绑定到 ListBox。请注意,该列表包含字符串数组 (string[])。

所以代码的 XAML 部分如下所示:

<ListBox Height="373" HorizontalAlignment="Left" Margin="9,65,0,0" Name="reservoirList" VerticalAlignment="Top" Width="546" 
                 ItemsSource="{Binding Wells}">
</ListBox>

在 viewModel 上:

public ObservableCollection<string[]> Wells {
            get { return new ObservableCollection<string[]>(getWellsWithCoords()); }            
        }

其中 getWellsWithCoords() 创建一个字符串 [] 列表。

当我运行应用程序时,我看到的是 - 这是有道理的:

string[] array
string[] array 
....

是否可以以这样一种方式更改 XAML 代码,以便在每一行上自动 我看到了 Wells 列表中每个元素的 n 个值,例如:

well1 value11 value12
well2 value21 value22

【问题讨论】:

    标签: c# wpf xaml data-binding listbox


    【解决方案1】:

    您可以实现自己的类来保存这些数据:

    public class WellInfo
    {
        private string[] _infos;
        public WellInfo(string[] infos)
        {
            this._infos = infos;
        }
        public string DisplayValue
        {
            get { return this._infos.Aggregate((current, next) => current + ", " + next); }
        }
    }
    

    在你的收藏中使用:

    public IEnumerable<WellInfo> Wells
    {
        get { return getWellsWithCoords().Select(x => new WellInfo(x)); }            
    }
    

    在 XAML 中:

    <ListBox 
        ItemsSource="{Binding Wells}" 
        DisplayMemberPath="DisplayValue" />
    

    【讨论】:

      【解决方案2】:

      将模板添加到您的列表框:

      <ListBox Height="373" HorizontalAlignment="Left" Margin="9,65,0,0" Name="reservoirList" VerticalAlignment="Top" Width="546" ItemsSource="{Binding Wells}">
      <ListBox.ItemTemplate>
          <DataTemplate>
              <!--Here you bind the array-->
              <ItemsControl ItemsSource="{Binding}">
                  <ItemsControl.ItemsPanel>
                      <ItemsPanelTemplate>
                          <StackPanel Orientation="Horizontal" />
                      </ItemsPanelTemplate>
                  </ItemsControl.ItemsPanel>
                  <ItemsControl.ItemTemplate>
                      <!--Here you bind the value of each string-->
                      <DataTemplate>
                          <TextBlock Text="{Binding}" Margin="5,0"/>
                      </DataTemplate>
                  </ItemsControl.ItemTemplate>
              </ItemsControl>
          </DataTemplate>
      </ListBox.ItemTemplate>
      

      【讨论】:

        猜你喜欢
        • 2011-10-14
        • 2011-07-10
        • 1970-01-01
        • 2017-04-14
        • 1970-01-01
        • 2014-01-31
        • 2011-08-28
        • 2012-10-21
        相关资源
        最近更新 更多