views:

174

answers:

3

Hello everyone,

I'm trying to bind to an item inside a collection but the index for that item needs to be "variable". Take the following pseudo syntax for example:

<TextBlock Text="{Binding Fields[{Binding Pos}]}" />

Is something like this possible? If my property Pos is 1 it should bind to the first item out of the collection "Fields" and if my Pos is 3 it should bind to the third item in the collection. I simplified my problem to this situation...

Is somethink like this doable and how? Thank you in advance. Jan

A: 

why don't you use a property that returns the current item in the collection and bind that to your WPF control?

such as:

class myCollection
{

    private string _current;

    public string CurrrentField
    {
         get { return _current; }
    }

    // TODO: Set current item to whatever the current item is...
}

EDIT:

In that case I think you'll need to create a helper class that tracks your columns in your data grid and aligns then with the items in your collection, so that the property that is bound to your UI gets updates correctly.

First fill up the collection, then you know how many items you have in it, then with the helper class loop through the collection and assign items to the property, then move onto the next column in your grid, etc...

I think it comes down to writing an algorithm for it yourself.

Tony
cause I´m using all elements from a collections but in different bindings. like i said, this is just a simplification of the problem itself.I´m using it in columns of a datagrid and i want all columns of the datagrid to use the same template (but the first column would have a binding to Fields[0], the second to Fields[1] etc. and i don´t know how many columns the ui will have in the future. that´s generated from a database). basically it comes down to solving the problem described above. but thanks for suggesting this possibilty.
Jan
+2  A: 

Yes, it is possible. You should implement binding converter that will convert collection to collection item and take index as converter parameter. Then you'll use it like this:

<TextBlock Text="{Binding Fields, 
                  Converter={StaticResource CollectionToItemConverter,
                  ConverterParameter={Binding Pos}}}" />

If you need a code for this converter or additional info about converters, please leave a comment.

Hope it helps.

levanovd
Thanks. This sounds really good to me.
Jan
Glad to hear it! =) Don't forget to accept the answer if this worked for you. =)
levanovd
Some day, I will ask IValueConverter to marry me..
cwap
Thanx everone. Great community.
Jan
Sorry. I had to work around it the last time so i couldn't really test it. now i had a similar problem, tested it. didn't work cause ConverterParameter isn't a DependencyProperty.
Jan
+1  A: 

try reading on ICollectionView... it can helps u cause it can automatically gives u the index of the item to bound your text.

Chen Kinnrot