Click here to Skip to main content
14,208,035 members
Rate this:
 
Please Sign up or sign in to vote.
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>


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

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

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").
   
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)



Advertise | Privacy | Cookies | Terms of Service
Web04 | 2.8.190612.1 | Last Updated 6 Mar 2019
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100