简体   繁体   English

将列表框数据绑定到列表<string[]>

[英]Databinding listbox to a list<string[]>

I am having hard luck in trying to bind my property which is of type List to a ListBox through XAML. 我很难通过XAML尝试将我的属性List绑定到ListBox。 Note though that the list contains string arrays (string[]). 请注意,该列表包含字符串数组(string [])。

So the XAML part of code looks like this: 所以代码的XAML部分看起来像这样:

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

and on the viewModel: 并在viewModel上:

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

where getWellsWithCoords() creates a list of string[]. 其中getWellsWithCoords()创建一个string []列表。

When I ran the application what I see is - which makes sense: 当我运行我看到的应用程序时 - 这是有道理的:

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

Is it possible to change the XAML code in such a way so that automatically on each row I see the n values of the each element of the Wells list, ie something like: 是否可以以这样的方式更改XAML代码,以便在每行上自动查看Wells列表的每个元素的n个值,即:

well1 value11 value12
well2 value21 value22

Add a template to your listbox: 将模板添加到列表框中:

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

You could implement your own class for holding this data: 您可以实现自己的类来保存这些数据:

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

The use that in your collection: 您收藏中的用途:

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

and in XAML: 在XAML中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM