简体   繁体   中英

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. Note though that the list contains string arrays (string[]).

So the XAML part of code looks like this:

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

and on the viewModel:

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

where getWellsWithCoords() creates a list of 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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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