Address individual objects in an ItemsControl template in silverlight & C#
I have a silverlight application with an ItemsControl which shows a list of items with values and units assigned to them...
Some DataType 1.8 XY
Datatype2 15.6 Units
Other Datatype 1.8 XTZ
The issue I have is that the units are custom and hence I cannot know in advance how long they will be and I need them to line up as shown. So, on the fly, I want to address each of the unit textblocks, find the one with the largest width and set the rest to the same (or set the column to that width).
How can I address each of the textblocks generated in the items control individually in C#?
Here is the xaml so far
<ItemsControl Name="DataTypesGrid" ItemsSource="{Binding}" Margin="0" BorderBrush="{x:Null}" Foreground="White" Background="{x:Null}" IsEnabled="True">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical" Margin="0,2,0,0" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Width="Auto">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Wi开发者_运维知识库dth="*"></ColumnDefinition>
<ColumnDefinition Width="20"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name}" HorizontalAlignment="Left" Grid.Column="0" FontSize="15" />
<TextBlock Text="{Binding Value}" HorizontalAlignment="Right" Margin="0,0,4,0" FontSize="15" Grid.Column="1" />
<TextBlock Text="{Binding Unit}" HorizontalAlignment="Left" FontSize="15" Grid.Column="2" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Thanks for the help
Cap
First get hold of the code for the VisualTreeEnumeration
extension methods from here.
Now add a Name
property to your unit TextBlock in the data template Name="unitText"
.
Given the presence of the VisualTreeEnumeration
extension methods you can now create a "query" for the boxes:-
IEnumerable<TextBlock> unitBlocks = DataTypesGrid.Descendents()
.OfType<TextBlock>()
.Where(t => t.Name == "unitText");
You can hang on to unitBlocks
for as long as DataTypesGrid
exists. Using For Each
on it will return the latest contents of the ItemsControl
. You can use .ToList()
on it if you need to temporarily create a List<TextBlock>
.
精彩评论