Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a variable binding to a collection item possible

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 something like this doable and how?

like image 854
Jan Avatar asked Nov 30 '09 14:11

Jan


People also ask

What is two way binding in WPF?

Two way binding is used when we want to update some controls property when some other related controls property change and when source property change the actual control also updates its property.

How many types of binding are there in WPF?

WPF binding offers four types of Binding. Remember, Binding runs on UI thread unless otherwise you specify it to run otherwise. OneWay: The target property will listen to the source property being changed and will update itself.

How does data binding work in WPF?

Data binding is a mechanism in WPF applications that provides a simple and easy way for Windows Runtime apps to display and interact with data. In this mechanism, the management of data is entirely separated from the way data. Data binding allows the flow of data between UI elements and data object on user interface.


2 Answers

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.

like image 124
levanovd Avatar answered Nov 15 '22 06:11

levanovd


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

like image 38
Chen Kinnrot Avatar answered Nov 15 '22 07:11

Chen Kinnrot