0

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.

Ternary
  • 2,401
  • 3
  • 31
  • 54

2 Answers2

2

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]}"/>
Clemens
  • 123,504
  • 12
  • 155
  • 268
  • Thanks! Could you explain more why the TextBlock is simpler? – Ternary Mar 27 '12 at 22:12
  • See [here](http://stackoverflow.com/questions/59099/what-is-the-difference-between-the-wpf-textblock-element-and-label-control) and perhaps [here](http://joshsmithonwpf.wordpress.com/2007/07/04/differences-between-label-and-textblock/). – Clemens Mar 27 '12 at 22:19
  • I can't seem to the get binding working. The collection is an ObservableCollection in my data context class. It's not a StaticResource. – Ternary Mar 27 '12 at 22:22
  • Can the collection index be binded an enum val so there aren't magic numbers in the xaml? – Ternary Mar 28 '12 at 21:21
  • I'm afraid not, but you could check the [data binding how-to topics](http://msdn.microsoft.com/en-us/library/ms752039.aspx). – Clemens Mar 28 '12 at 21:44
0

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]; } }
one-t
  • 333
  • 3
  • 13