Click here to Skip to main content
15,942,964 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi, I am trying to learn WPF. The DataContext is set to ViewModel. In Itemscontrol I am getting a list<string> named"MyList". By default the datacontext of datatemplate would be string. So I modified the datacontext of TextBlock to Viemodel to access the property MyWidth which is binded to "Width". Actually the number of values of "MyWidth" is equal to number of elements in the list "MyList".MyWidth is also a list.Now I do not know how I can get all the values of MyWidth.
Cold you please help me out. I will be grateful to you guys.

What I have tried:

<ItemsControl ItemsSource="{Binding MyList}">
                           <StackPanel Name="horizontalLabels" Orientation="Horizontal"  />


                           <TextBlock     Text="{Binding}"

                                         Width="{Binding DataContext.LabelWidth, RelativeSource={RelativeSource AncestorType=ItemsControl},UpdateSourceTrigger=PropertyChanged}"
                                          Background="Red" Height="30"  FontSize="12"



public void AddLabels(double parameters)
        { MyList.Add("dummy");
Updated 6-Mar-19 4:57am

1 solution

Create a class for your "string" and "width".

Load a collection (List<> or ObserveableCollection<>) with instances of that class.

Set the ItemSource to this collection.

Bind the TextBlock "Text" and "Width" to the corresponding properties of the new "string and width" class.

(What you're currently trying to do with Width "does not compute").
Share this answer
hamid18 6-Mar-19 11:24am    
thanks. This looks simple and i hope this will work.
hamid18 15-Mar-19 9:36am    
It worked smoothly. Thanks a lot :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900