Click here to Skip to main content
15,936,169 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}">
                   <ItemsControl.ItemsPanel>
                       <ItemsPanelTemplate>
                           <StackPanel Name="horizontalLabels" Orientation="Horizontal"  />

                       </ItemsPanelTemplate>
                   </ItemsControl.ItemsPanel>
                   <ItemsControl.ItemTemplate>
                       <DataTemplate>

                           <TextBlock     Text="{Binding}"

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

                                           >
                           </TextBlock>

                       </DataTemplate>
                   </ItemsControl.ItemTemplate>
               </ItemsControl>


C#
public void AddLabels(double parameters)
        { MyList.Add("dummy");
MyWidth.Add(30);
MyList.Add("dummy2");
MyWidth.Add(60);}
Posted
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
 
Comments
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