WPF: Synchronize width of all items in ItemsControl - c#

Is it possible to adjust the width of all TextBlocks in the WrapPanel to the size of the largest TextBlock within the WrapPanel? The end result should be that the width of the control containing "Some data" has the same width as the control containing "Even more data than before." I have attached to my initial code as a starting point. I have used strings as an example, but the collection data and template could be anything, so I can't rely on the length of the string.
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:Collections="clr-namespace:System.Collections;assembly=mscorlib"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Collections:ArrayList x:Key="data">
<System:String>Some data</System:String>
<System:String>Some more data</System:String>
<System:String>Even more data than before</System:String>
</Collections:ArrayList>
</Window.Resources>
<ItemsControl ItemsSource="{StaticResource data}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel></WrapPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Margin="5" BorderThickness="1" BorderBrush="Black">
<TextBlock Text="{Binding}"></TextBlock>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Window>
And an image of the desired output:

Use a shared size grid:
<ItemsControl ItemsSource="{StaticResource data}" Grid.IsSharedSizeScope="True">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel></WrapPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="ColumnSize" />
</Grid.ColumnDefinitions>
<Border Margin="5" BorderThickness="1" BorderBrush="Black">
<TextBlock Text="{Binding}"></TextBlock>
</Border>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
All columns are guaranteed to be the same width as they share a size group. As they are sized auto, they will also size to the largest instance of any of the grid's content.

You have to create your own custom version of a wrappanel that is derived from wrappanel to achieve what you want.
Normally for a custom panel you have to override following 2 methods :
MeasureOverride
ArrangeOverride
In your case you need measueoverride where you will iterate over the elements and find out which one is the biggest and then use that same size for all elements in arrangeoverride.
Some more info on how to create a custom panel :
http://www.wpftutorial.net/CustomLayoutPanel.html

You can add HorizontalContentAlignment=Stretch and Add UniformGrid in itemsPanel.
<Window.Resources>
<Collections:ArrayList x:Key="data">
<System:String>Some data</System:String>
<System:String>Some more data</System:String>
<System:String>Even more data than before</System:String>
</Collections:ArrayList>
</Window.Resources>
<ListBox ItemsSource="{StaticResource data}" HorizontalContentAlignment="Stretch">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid IsItemsHost="True"></UniformGrid>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Border Margin="5" BorderThickness="1" BorderBrush="Black" >
<TextBlock Text="{Binding}" Width="{Binding
RelativeSource={RelativeSource TemplatedParent},
Path=Width}"></TextBlock>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

This is an alternative to Philip Stuyck's custom panel suggestion that you may find more straightforward for your particular scenario. (It is a bit of a hack admittedly.)
You can calculate the length of a string using the FormattedText class. So you could iterate over your strings and calculate the maximum length (this also assumes that you know the font family and size). Then just bind the width of your text blocks to the maximum width. I would store the width value in a single property at the parent level, then using a RelativeSource binding:
<TextBlock Text="{Binding}"
Width="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl},
Path=MaximumWidth}}"
/>
(One drawback of this approach is that if the items collection changes, you'll have to recalculate MaximumWidth.)

Related

WrapPanel hides half of the last uiElement of each line

Each UserControl I have in a stackPanel has a WrapPanel, and each UserControl in this WrapPanel is a word (so they have a different size from each other, depending on the length of the word), so that a sentence appears.
Here is an image to help you understand better:
In pink it is the UserControl "sentence" that contain each of them ONE wrapPanel
In Green it is all the UserControl "word" that have all different size according to the word length.
Here is the UserControl "word":
<UserControl x:Class="Coran_seul.UC.UserControl_WordInVerse"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Coran_seul.UC"
mc:Ignorable="d" Margin="5,0,5,0">
<StackPanel>
<TextBlock x:Name="textBlock_arabic" Text="ٱلْأَنفَالُ " FontSize="20" HorizontalAlignment="Center" FontFamily="Noto Naskh Arabic" MouseEnter="textBlock_arabic_MouseEnter" MouseLeave="textBlock_arabic_MouseLeave" Cursor="Hand" MouseDown="textBlock_arabic_MouseDown"/>
<TextBlock x:Name="textBlock_french" Text="Les surplus (de bénéfice)" FontSize="20" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</StackPanel>
And here is the UserControl "sentence" (with the wrapPanel I have a problem with)
<UserControl x:Name="userControl" x:Class="Coran_seul.UC.UserControl_VerseInSurah"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Coran_seul.UC"
mc:Ignorable="d" Margin="0,5,0,5"
>
<Border x:Name="Border_Verse" >
<StackPanel Orientation="Horizontal" x:Name="grid">
<Label x:Name="Label_VersetNum" Content="2" Height="{Binding ActualHeight, ElementName=WrapPanel_Mots, Mode=OneWay}" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" VerticalAlignment="Stretch" HorizontalAlignment="Left" MouseDown="Label_VersetNum_MouseDown"/>
<WrapPanel x:Name="WrapPanel_Mots" Width="{Binding ActualWidth, ElementName=userControl, Mode=OneWay}" />
</StackPanel>
</Border>
The problem :
Now that I've entered the code, here's the problem I'm having with my wrapPanel:
The last word of each line does not wrap, even if it is larger than the space left (= it is therefore hidden/cut off at the edge of the wrapPanel)
Again I have a video to better explain the problem :
https://streamable.com/lpdf38
I don't know what it's due to and I'm desperately looking since yesterday not to have this problem anymore, knowing that the stackPanel containing all the userControls has a right margin of 20 so that it's not hidden behind the scrollbar.
Please help me to find a solution so that the word as long as it is hidden even by one pixel is wrapped to the next line.
Thank you,
The problem is that you bind the WrapPanel's Width to that of its UserControl parent without subtracting the Width of the Label element.
You should not need to bind any Width at all, when you use suitable Panel elements, like e.g. a Grid or a DockPanel instead of StackPanel.
<Border x:Name="Border_Verse">
<DockPanel>
<Label x:Name="Label_VersetNum" DockPanel.Dock="Left" .../>
<WrapPanel x:Name="WrapPanel_Mots">
</DockPanel>
</Border>
<Border x:Name="Border_Verse">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Label x:Name="Label_VersetNum" Grid.Column="0" .../>
<WrapPanel x:Name="WrapPanel_Mots" Grid.Column="1">
</DockPanel>
</Border>
You may also consider to use an ItemsControl to display a sentence. It would use a WrapPanel as its ItemsPanel and the word UserControl in its ItemTemplate:
<ItemsControl ItemsSource="{Binding Words}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<uc:UserControl_VerseInSurah/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
where Words is a collection of word data item objects in the view model, i.e. the object in the DataContext of the view. The two TextBlocks in the word UserControl would have their Text property bound to an appropriate property on the word data item class.
You may not even need the word UserControl at all, since you can simply move the elements from its XAML into the DataTemplate that is used as ItemTemplate.
See Data Templating Overview for details.

UniformGrid reduce spacing between rows in WPF

I am using a WPF UniformGrid to bind alist of items and the xaml is like this
<ListBox Name="lviewSearch" ItemsSource="{Binding SearchSettingsCollection}" SelectionMode="Multiple">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="2"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<ItemsControl Margin="3" Padding="5">
<DockPanel>
<Label Content="{Binding Label}" HorizontalAlignment="Stretch" Cursor="Hand" />
</DockPanel>
</ItemsControl>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
But if the no of items is less then the spacing between rows is too much like this
http://i.stack.imgur.com/Xr5qy.png
How can i ireduce thi s?
Like people said, your UniformGrid has too much vertical space so it expands the rows to take up all that space (stretches).
What you need to do is prevent this default behavior of stretching by setting
VerticalAlignment="Top"
The whole point of the UniformGrid is that the size of cells is uniform and therefore the same size. If you only have a small number of rows compared to the vertical space then each row is going to be pretty tall. Conversely if you have many rows and little vertical space then each row becomes tiny. If this is not an appropriate appearance then you need to use a different method of laying out.
Without knowing much more about the visual design it becomes impossible to recommend a possible alternative. Is the ListBox always the same size or will it vary in height? Does the number of displayed results vary or stay constant? All these change how you might achieve the required result.
One simple solution is to use grid outside Listbox. Set row height as auto. Now Uniform grid will take minimum space as required.
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ListBox Name="lviewSearch" ItemsSource="{Binding SearchSettingsCollection}" SelectionMode="Multiple">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="2"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<ItemsControl Margin="3" Padding="5">
<DockPanel>
<Label Content="{Binding Label}" HorizontalAlignment="Stretch" Cursor="Hand" />
</DockPanel>
</ItemsControl>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>

Xaml code explanation

I am working on c# xaml using silverlight and i am bit confused about the hierarchy of this xaml code:
<UserControl.Resources>
<this:MyValueConverter x:Key="TabConverter"/>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="Green">
<ItemsControl ItemsSource="{Binding Path=TabList, Mode=OneWay}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas></Canvas>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Width="150" Background="red" Height="100" Canvas.Left="{Binding TabList, Mode=TwoWay, Converter={StaticResource TabConverter}}" Canvas.Top="100" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
When i run it gives a big green color window(sorry if technical names are not correct), whereas it should also show red color somewhere in same window as it has Border Width="150" Background="red" .Could some one please explain me what this code is doing ?
ItemsControl really just binds to a list and applies a datatemplate (border with background red) for each item in the list. As for the reason you're only seeing green, well there's probably nothing in the TabList property on your viewmodel. That way, nothing in the items template renders, and all you see is green.
You'll need to make sure that TabList is bound correctly (it exists on your datacontext, whether that's a view model or not) and that it has items in it.
Here's a simpler version of what you may want to accomplish:
<Grid x:Name="LayoutRoot" Background="Green">
<ItemsControl ItemsSource="{Binding Path=TabList, Mode=OneWay}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Width="150" Background="red" Height="100" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>

Add extra element to ItemsControl's Canvas

I have an ItemsControl set up like this:
<Grid>
<ItemsControl ItemsSource="{Binding Asteroids}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Background="Black">
<!-- i want to add another polygon to the canvas-->
<!--<Polygon Name ="ShipPolygon" Points="{Binding Ship}" Fill="Blue" />-->
</Canvas>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Polygon Fill="Gray" Points="{Binding AsteroidPoints}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
As you can see, the ItemsControl is displaying a collection's elements as Polygons in a Canvas. But i also want to add another Polygon to this Canvas, here named "ShipPolygon". I can't do that this way, because i get an XMLParseException. What is the proper method to do this? Thanks in advance!
You are using an ItemsControl, which is there to display multiple similar items on an itemspanel.
Now obviously you can't add something to your ItemsPanelTemplate there you are only telling the itemscontrol which panel it should use to display its items.
Your ItemsSource and your ItemTemplate suggest that you only want to show Asteroids in your ItemsControl. So the easiest way would be to just overlay your ship onto the itemscontrol with your asteroids
<Grid>
<ItemsControl ItemsSource="{Binding Asteroids}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Background="Black"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Polygon Fill="Gray" Points="{Binding AsteroidPoints}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Polygon Name ="ShipPolygon" Points="{Binding Ship}" Fill="Blue" />
</Grid>
Otherwise you could add it aswell to the itemscontrol, but then need to use different ItemTemplates. And you need to handle, that your ItemsControl no longer only holds Asteroids.
Using implicit item Templates
<!-- No key, so it is implicit and automatically used-->
<DataTemplate DataType="{x:Type Asteroids}">
<Polygon Fill="Gray" Points="{Binding AsteroidPoints}" />
</DataTemplate>
<DataTemplate DataType="{x:Type Player}">
<Polygon Name ="ShipPolygon" Points="{Binding Ship}" Fill="Blue" />
</DataTemplate>
<!-- above must be in a resource section, like app.xaml -->
<Grid>
<ItemsControl ItemsSource="{Binding Entities}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Background="Black"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Grid>
Or you could use a DataTemplateSelector.

Binding a list to a flow of WrapPanels

I am trying to do an interface in WPF where a list of item is displayed, taking as little vertical space as possible:
My instinct was to use an ItemsControl to bind my list, and to put the UI for each item into a WrapPanel. Unfortunately by default, each item starts at a new line regardless of the window's size. Adding a StackPanel with Orientation="Horizontal" makes all items in a single line, regardless of the size...
<!--<ScrollViewer Grid.Row="0" Grid.Column="0"
VerticalScrollBarVisibility="Auto">-->
<ItemsControl Margin="0,4" ItemsSource="{Binding Path=Watchers}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"></StackPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type Core:Watcher}">
<WrapPanel Orientation="Horizontal">
<TextBlock Margin="0,2" Text="{Binding Path=Name}"
Width="250px" />
<TextBox Text="{Binding Path=Value, Mode=OneWay}"
Width="300px">
</TextBox>
</WrapPanel>
</DataTemplate>
</ItemsControl.Resources>
</ItemsControl>
<!--</ScrollViewer>-->
Any pointers?
Bonus point: Where should I add a ScrollViewer in order to have the behavior shown in my mockup?
Thanks a lot!
The WrapPanel has, as well as the StackPanel, an Orientation property, which defaults to Vertical. So your list should wrap (assuming you have enough space at hand) if your ItemsPanelTemplate looks like this:
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
About the ScrollViewer:
The desired behavior should be achieved by defining it like follows (not tested though, and I omitted all for this example unnecessary stuff):
<ScrollViewer HorizontalAlignment="Stretch">
<ItemsControl MinWidth="550" Width="{Binding ActualWidth, Mode=OneWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ScrollViewer}}}" />
</ScrollViewer>
I think you want the WrapPanel in the ItemsPanel and the StackPanel in the ItemTemplate.
why not use the WrapPanel as ItemsPanelTemplate?
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
as long as the items have space to the left they would be arranged horizontal.

Categories