Ternary
Ternary

Reputation: 2411

Grid of Labels Bind Content

I have a <Grid> set up just the way I want with each cell containing a <Label>.

I want this because I want the labels to have a fixed position on the screen. For example, if I have an array {"One, "Two", "Three"} it should go on screen as:

[ One ]________ [ Two ] ________ [ Three ]

If that array is {"One, "Three"}, I want the space for two reserved like so:

[ One ] ______________________ [ Three ]

The grid handles this nicely.

Now I want to bind the content of those labels to a structure in the code-behind and am struggling to get the label to bind to a specific index of the ObservableCollection in my code-behind.

Upvotes: 0

Views: 136

Answers (2)

Clemens
Clemens

Reputation: 128013

Simply bind like this (if your collection is defined as resource):

<Label Content="{Binding Source={StaticResource myCollection}, Path=[0]}"/>
<Label Content="{Binding Source={StaticResource myCollection}, Path=[1]}"/>

and perhaps use the simpler TextBlock instead:

<TextBlock Text="{Binding Source={StaticResource myCollection}, Path=[0]}"/>
<TextBlock Text="{Binding Source={StaticResource myCollection}, Path=[1]}"/>

If your collection is a property of your DataContext object (e.g. named Collection) bind like this:

<Label Content="{Binding Path=Collection[0]}"/>
<Label Content="{Binding Path=Collection[1]}"/>

Upvotes: 2

one-t
one-t

Reputation: 333

You could expose properties that return the value at the indexes you want from the collection. Eg. Bind One to something like:

public string OneValue { get { return Collection[0]; } }

Upvotes: 0

Related Questions