Wrapping panels in WPF - wpf

I have the following layout in my window:
Grid with two columns
GridSplitter which resizes grid columns
Second grid column is filled with StackPanel
StackPanel is oriented vertically and has 2 children: TextBlock and a WrapPanel
WrapPanel has two Grids as children
First Grid child contains one Image
Second Grid contains a StackPanel with 3 TextBlocks oriented vertically.
The XAML code looks like this:
<Window>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<GridSplitter Grid.Column="1" Width="5" HorizontalAlignment="Left" />
<StackPanel Grid.Column="1" Margin="5,0,0,0" Orientation="Vertical"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<TextBlock Text="Now here's a silly poem for you." />
<WrapPanel>
<Grid Name="GridForImage">
<Image Width="200" Height="200" Source="Image.jpg" />
</Grid>
<Grid Name="GridForText">
<StackPanel Orientation="Vertical">
<TextBlock TextWrapping="WrapWithOverflow" Text="Roses are red." />
<TextBlock TextWrapping="WrapWithOverflow" Text="Violets are blue." />
<TextBlock TextWrapping="WrapWithOverflow" Text="You belong in a zoo." />
</StackPanel>
</Grid>
</WrapPanel>
</StackPanel>
</Grid>
</Window>
Once the window opens, the second column is wide enough to allow grids GridForImage and GirdForText to be placed next to each other horizontally. If I shrink the width of the second column using the grid splitter, the GridForText grid gets placed underneath the GridForImage at one point, which is quite expected.
Here's what I would like to achieve:
I want GridForText to shrink its width to a certain size and to remain positioned to the right of the GridForImage, as I move the grid splitter to the right side of the window. Then, when the width shrinks to a certain value, say 200px, it should get placed underneath the GridForImage, i.e. WrapPanel should do its magic. Right now, the GridForText doesn't resize at all, it just gets placed underneath when it's current width becomes too large for the width of the WrapPanel.
When the GridForText does get placed underneath the GridForImage, I want GridForImage to fill the entire width of the WrapPanel's width.
Is all this possible and what should I do? Thank you all.

You're essentially trying to use two distinct layout modes so you just need to set up the two distinct states in your layout and then add bindings or triggers to switch between them at the point when you want to switch modes (i.e. width = 200). Using a Grid is the most flexible and gives you a lot more control over the relative sizes but requires more settings and would work best in a ControlTemplate or DataTemplate where you can use Triggers to set a bunch of things at once based on a condition.
Here's a more compact example using UniformGrid with some Bindings and a converter. I removed the fixed sizing on the Image - try Stretch="Fill" if you care more about filling width than aspect ratio. I also changed one StackPanel to a DockPanel to maintain vertical stretching for its children and added a Background to one of the TextBlocks just to show how much Width it's really getting:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<GridSplitter Grid.Column="1" Width="5" HorizontalAlignment="Left" />
<DockPanel Grid.Column="1" Margin="5,0,0,0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<TextBlock Text="Now here's a silly poem for you." DockPanel.Dock="Top"/>
<UniformGrid Rows="{Binding RelativeSource={RelativeSource Self}, Path=ActualWidth, Converter={x:Static local:LayoutModeConverter.Row}, ConverterParameter=200}"
Columns="{Binding RelativeSource={RelativeSource Self}, Path=ActualWidth, Converter={x:Static local:LayoutModeConverter.Column}, ConverterParameter=200}">
<Image Source="Image.jpg" />
<StackPanel Orientation="Vertical">
<TextBlock TextWrapping="WrapWithOverflow" Text="Roses are red." Background="Red" />
<TextBlock TextWrapping="WrapWithOverflow" Text="Violets are blue." />
<TextBlock TextWrapping="WrapWithOverflow" Text="You belong in a zoo." />
</StackPanel>
</UniformGrid>
</DockPanel>
</Grid>
And the converter:
public class LayoutModeConverter : IValueConverter
{
public static readonly LayoutModeConverter Row = new LayoutModeConverter { RowMode = true };
public static readonly LayoutModeConverter Column = new LayoutModeConverter { RowMode = false };
public bool RowMode { get; set; }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
double width = System.Convert.ToDouble(value);
double targetWidth = System.Convert.ToDouble(parameter);
if (RowMode)
return width > targetWidth ? 1 : 2;
else
return width > targetWidth ? 2 : 1;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}

Related

WPF XAML ListView - Make TextBlock Text wrap

I have a ListView with ListView.ItemTemplate like this
<ListView
x:Name="myList"
BorderBrush="Transparent"
ItemsSource="{Binding MyItems}"
SelectedIndex="0"
ScrollViewer.CanContentScroll="True"
ScrollViewer.VerticalScrollBarVisibility="Auto">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="Padding" Value="0" />
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="5,5,5,5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/> <--THIS WILL FORCE WRAPPING
<ColumnDefinition Width="50"/>
</Grid.ColumnDefinitions>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Text="{Binding FilePath}"
Grid.Row="0" Margin="3,3,3,3"
Style="{StaticResource MyFilePathTextLabel}"
TextWrapping="WrapWithOverflow"/> <-- THIS WILL NOT WRAP TEXT
<StackPanel Orientation="Horizontal" Grid.Row="1" Margin="3,3,3,3">
<TextBlock Text="Lab location: "/>
<TextBlock Text="{Binding LabLocation}"
Style="{StaticResource MyLabLocationTextLabel}"/>
</StackPanel>
...
...
</DataTemplate>
</ListView.ItemTemplate>
...
...
</ListView>
This will show ListView items like this:
----------------------------------
C:/samples/folderA/myfile1.txt <-- NO WRAP AS IT FITS
Lab location: Chemistry Lab 301
----------------------------------
C:/samples/folderA/folderB/fold
erC/folderD/folderE/folderF/myf
ile2.txt <-- WRAP SINCE NOT FITTING
Lab location: Chemistry Lab 301
----------------------------------
C:/samples/folderA/folderB/myfi
le3.txt <-- WRAP SINCE NOT FITTING
Lab location: Chemistry Lab 301
----------------------------------
C:/samples/folderA/folderB/fold
erC/folderD/folderE/folderF/fol
derG/folderH/folderI/folderJ/fo
lderK/myfile4.txt <-- WRAP SINCE NOT FITTING
Lab location: Chemistry Lab 301
----------------------------------
C:/samples/myfile5.txt <-- NO WRAP AS IT FITS
Lab location: Chemistry Lab 301
----------------------------------
Above, each item show file location as wrapped if it does not fit the width of the ListView.
UPDATE:
Updated XAML
UPDATE 2:
Setting the column Width of grid container to hardcoded value of will force wrapping (see above commented line). But since form is resizable, the grid and ListView is also resizable. Therefore, I can not hardcode width. It needs to wrap according to the current size of the form.
Set the HorizontalContentAlignement="Stretch" on the ListView object itself to tell it to stretch it's Content horizontally to fit available space, and set the HorizontalScrollBarVisiblilty to Disabled to make sure horizontal scrolling is disabled.
<ListView x:Name="myList" ...
HorizontalContentAlignment="Stretch"
ScrollViewer.HorizontalScrollBarVisibility="Disabled">
If you use a Grid and set <ColumnDefinition Width="*">, the GridColumn enlarges as much as possible to fill all the available space. Only and only after that, other operations like wrapping take place.
In this case, the GridColumn becomes large enough to contain all the text on a single line. And that's the reason why the text doesn't wrap: it doesn't need to wrap! It has all the space it needs to stay on a single line!
SOLUTION: Set a fixed column width, as 200, or 100, or anyway try a smaller width, and see the result. At some point the text MUST wrap, with a GridColumn thin enough.
SOLUTION FOR FLEXIBLE WIDTH:
You have to bind the Width of the inner Grid (the one with the RowDefinitions) to the ActualWidth of the outer Grid (the one with the ColumnDefinitions).
Create a converter like this:
public class OuterGridToInnerGridWidthConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((double)value) / 2;
}
}
In this example I suppose that the inner Grid has half the Width of the outer. If instead you have the column of the Grid with Width="*" and the second column with a fixed width of - for example - 50, the converter can be:
public class OuterGridToInnerGridWidthConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((double)value) - 50;
}
}
Made this, add this attribute to the inner Grid:
Width="{Binding ActualWidth,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Grid}},
Converter={StaticResource OuterGridToInnerGridWidthConverter}}"
Finally, set HorizontalContentAlignment="Stretch" for the ListView.
This works both when you make the window smaller or bigger: the TextBlock resizes and wraps correctly.
Can you try to have the first RowDefinition like :
<RowDefinition Height="Auto"/>
instead of
<RowDefinition Height="*"/>
?
If no success, try temporarily removing the
Style="{StaticResource MyFilePathTextLabel}"
also. You did not share its code, so I'm thinking it might break the wrapping.

WPF ContentControl does not collaspe on Visibility change

I have a tab sequence that I want to be able to split into two regions or recombine into a single tab sequence. The application will start off with one tab sequence
Allow the user to split into a second panel
And recombine into a single tab control.
At this stage, I should get the same display at the first image. But, instead, the ContentControl does not Collaspe and space is left in the main Grid. There is also a GridSplitter that devides the two areaa (white bar in image 2). That seems to Collapse as expected. Is there some trick to get it to get the ContentControl to Collapse?
Here's the XAML. There's a boolean property BottomTabDisplayed which indicates if there are any controls in the bottom area:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ContentControl x:Name="ControlContainerTopTab" Grid.Row="0">
<TabControl SelectedIndex="{Binding SelectedIndex}"
>
<TabControl.ItemContainerStyle>
...
</TabControl.ItemContainerStyle>
</TabControl>
</ContentControl>
<GridSplitter x:Name="GridSplitterTabControls"
Grid.Row="1"
Height="5"
HorizontalAlignment="Stretch"
VerticalAlignment="Center"
Visibility="{Binding BottomTabDisplayed,
Converter={StaticResource VisiblityToBoolConverter}}" />
<ContentControl Grid.Row="2" Visibility="{Binding BottomTabDisplayed, Converter={StaticResource VisiblityToBoolConverter}}">
<TabControl SelectedIndex="{Binding SelectedBottomIndex}"
Visibility="{Binding BottomTabDisplayed,
Converter={StaticResource VisiblityToBoolConverter}}"
>
<TabControl.ItemContainerStyle>
...
</TabControl.ItemContainerStyle>
</TabControl>
</ContentControl>
</Grid>
Edit 1:
And, here's the converter
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool isVisible = (bool)value;
return (isVisible ? Visibility.Visible : Visibility.Collapsed);
}
I just noticed something interesting, if the GridSplitter is unchanged, it works as expected. If I move the GridSplitter, then I get the empty space.
Edit 2:
Snoop changes when moving the GridSplitter
If you look at your code for VisiblityToBoolConverter, you will very likely see it is returning Hidden instead of Collapsed

Textbox will not stretch to fill viewbox

I want the font size of my labels and textboxes in my LOB form to grow and shrink with window resize or resolution change. To achieve this I've placed my labels and textboxes within viewboxes.
The labels and custom radio buttons behave as I expect, but the textboxes will not stretch horizontally to fill the viewbox (sorry can't post image because of rep). The textboxes will horizontally fill the viewbox if you type into them.
Here is an example of the code which I am working with:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.186*"/>
<ColumnDefinition Width="0.814*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="0.127*"/>
<RowDefinition Height="0.873*"/>
</Grid.RowDefinitions>
<Viewbox Margin="0,0,0.917,0">
<Label Content="First name:"/>
</Viewbox>
<Viewbox Grid.Column="1">
<TextBox TextWrapping="Wrap"/>
</Viewbox>
</Grid>
I've tried placing grid, stackpanel and dockpanel (with LastChildFill="True") within the viewbox and then placing the textboxes within these layout controls but this didn't work either. Is there anyway to get the textboxes to horizontally fill the parent viewbox?
This problem is similar to this: WPF TextBox won't fill in StackPanel but this problem is with stackpanels, not viewboxes.
I think what you want is not easily possible. ViewBox tells its children that they have inifite space, in the measure pass of the layouting. After that, the display is fit into the viewbox. Now a textbox, told to have infinite space, obviously can't stretch.
I have 2 solutions, which i think are not what you want, but might be helpful anyway.
The first:
<Viewbox Grid.Column="1" Grid.Row="0" Stretch="Uniform" >
<Grid Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Viewbox}}, Path=ActualWidth}">
<TextBox TextWrapping="Wrap" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
</Grid>
</Viewbox>
this will stretch you textbox infact, but disable the behaviour expected from the viewbox. Why? We told the ViewBox to keep the aspect ratio, and set the textbox to fill the whole width of the viewbox, which keeps the size of the textbox.
The second:
would be to add a height to the grid, taken from the label, modified with the scaletransform of its viewbox.
This one i haven't tried, but it would involve a value converter.
In conclusion: There is no easy way to achieve what you want, because of the way the viewbox layouts its children. If you just want to stretch horizontally, my first solution works fine, if you want to scale. My guess is you have to do it yourself.
If what you want doesn't work/isn't easy then fake it:
<TextBox GotFocus="TextBox_GotFocus" HorizontalAlignment="Stretch" BorderThickness="0" Grid.Column="1"/>
<Viewbox HorizontalAlignment="Left" Stretch="Uniform" Grid.Column="1">
<TextBox x:Name="NameTextBox" Width="50" TextWrapping="Wrap" Text="Text" BorderThickness="0"/>
</Viewbox>
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
NameTextBox.Focus();
NameTextBox.SelectionStart = NameTextBox.Text.Length;
}
Basically what happens is another TextBox is behind the Viewbox and when the behind TextBox gets focus, it switches focus to the Viewbox's TextBox. This will produce some odd resizing since you have your grid setup with relative sizes. You will need to play around with your grid column/width sizes until you get the effect you desire.
Just use a converter
Set the FontSize like this:
FontSize="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight ,Converter={StaticResource heightconverter}, ConverterParameter=3}"
public class ProcentualHeightConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (parameter is string p)
{
if (value is double v)
{
var result = double.TryParse(p, out double param);
if (result)
{
return v / param;
}
}
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}

Prevent a TextBox from horizontal expanding in WPF

I have the following style defined in my App.xaml
<Style x:Key="textBoxMultiline" TargetType="{x:Type TextBox}" >
<Setter Property="VerticalScrollBarVisibility" Value="Auto" />
<Setter Property="HorizontalScrollBarVisibility" Value="Hidden" />
<Setter Property="MinHeight" Value="50" />
<Setter Property="TextWrapping" Value="Wrap" />
</Style>
And throughout the solution we're using it on every text box that needs a brief text.
<TextBox x:Name="textBoxDescription" Grid.Row="2" Grid.Column="1" Style="{DynamicResource textBoxMultiline}" />
Everything works great, but then the client complains about some fields were corped on older monitors with lower resolutions, so I placed a ScrollViewer on one of the higher visual tree nodes to prevent the corping.
<ScrollViewer Height="Auto" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">
...
</ScrollViewer>
Strangely, the TextBoxes with the above style start expanding to the right instead of wrapping the text.
Is there a way to prevent this without removing the ScrollViewer?
If you don't want to hard code the width then you can go for element binding the width of the parent item.
Here I am binding TextBox MaxWidth with ScrollViewer actual width. You also have to make sure that the ColumnDefinition width should be set to "*" not to "Auto". If you set it to Auto it will neglect the ScrollViewer width and keep on expanding the width of ScrollViewer and TextBox. I think you fall in this case...
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<ScrollViewer HorizontalScrollBarVisibility="Auto" Name="scv">
<TextBox Height="30" TextWrapping="Wrap" MaxWidth="{Binding ElementName=scv, Path=ActualWidth}"></TextBox>
</ScrollViewer>
</Grid>
You must define a MaxWidth for the TextBox, otherwise there's no limit because the ScrollViewer.
The solution provided from #bathineni helped me solve my problem. Here is what worked for me:
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Grid.Column="0" Width="30" Height="23" Margin="10,5" Content="..."/>
<ScrollViewer Grid.Column="1" HorizontalScrollBarVisibility="Disabled" verticalScrollBarVisibility="Disabled" Name="scv">
<TextBox Height="25" Text="Insert here long text" MaxWidth="{Binding ElementName=scv, Path=ActualWidth}" HorizontalAlignment="Stretch" />
</ScrollViewer>
</Grid>
I tried the aforementioned examples and they didn't work so, I solved the problem myself. There are two ways of solving this issue:
The first solution is implemented in XAML using data bindings. I advice you not to bind the control by itself. The XAML solution is implemented by binding a control with the desired ActualWidth and ActualHeight proprieties to the textbox MaxHeight and MaxWidth proprieties.
<TextBlock x:Name="PasswordText" Margin="0,0,0,20" FontFamily="Bahnschrift SemiBold Condensed" Text="PASSWORD" FontSize="20">
<TextBox x:Name="PasswordTextBox" MaxWidth="{Binding ElementName=PasswordText, Path=ActualWidth}" MaxHeight="{Binding ElementName=PasswordText, Path=ActualHeight}">
The next solution is implemented by generating a Loaded event in XAML, creating it in the C# code and then setting within the Loaded event the MaxWidth and MaxHeight proprieties of the textbox as the textbox ActualWidth and ActualHeight proprieties.
// It doesn't have a problem like in XAML if you pass the textbox its own
// ActualWidth and ActualHeight to the MaxWidth and MaxHeight proprieties.
private void Log_In_Page_Loaded(object sender, RoutedEventArgs e)
{
UsernameTextBox.MaxHeight = UsernameTextBox.ActualHeight;
UsernameTextBox.MaxWidth = UsernameTextBox.ActualWidth;
}
Choose the one that suits your design better, but I think, in my opinion, that this is the most effective, simple, stable and effective way of solving this problem.
Works for me. If you want scrollbars to appear in the textbox, you may add
HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"
to the TextBox
You must set MaxWidth of the Container Control
<Grid x:Name="RootGrid" Margin="6,6,8,8" Width="500" MaxWidth="500">
<ScrollViewer ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<GroupBox Name="contentGroup" Header="Content" Grid.Row="0">
<TextBox Name="content"/>
</GroupBox>
</Grid>
</ScrollViewer>
I ran into this problem when I needed my TextBox to stretch along with its auto-sized Grid column when it got resized, meaning MaxWidth wouldn't work, but still needed to prevent the TextBox from stretching along with its contents.
What I ended up doing was linking this event handler to SizeChanged:
private void TextBox_SizeChanged(object sender, SizeChangedEventArgs e) {
TextBox textBox = (TextBox)sender;
if (textBox.CanUndo && e.NewSize.Width > e.PreviousSize.Width) {
textBox.Width = e.PreviousSize.Width;
}
}
Writing text to a textbox is something that the user can Undo, whereas other actions that can cause resizing (initial drawing of the element, stretching of parent container, etc) aren't Undoable from within the textbox. Thus, by checking CanUndo we can determine whether SizeChanged was triggered by writing text or something else.
The e.NewSize.Width > e.PreviousSize.Width check is necessary because without it the SizeChanged event will infinitely be called from within itself, because to revert the stretching we need to change the size back to the original, which would itself trigger the event.
It's a little hacky but I haven't run into any issues yet.
I am not sure why but I could not get the ScrollViewer solution to work. I needed to have a TextBox with a fixed initial width to implement a numeric up/down control - in this control the TextBox was shrinking and growing independent of the input which looks very annoying if the UI changes as you type.
So, I found the below solution using 2 textboxes to work for me. The first textbox is the textbox displayed for the user to type their input and the 2nd textbox is initialized through a dependency property (DisplayLength) and the converter shown further below.
Binding the MaxWidth property of the 1st TextBox to the Width property of the 2nd TextBox fixes the size such that users can type what they want but the displayed width of the textbox will not change even if there is more UI space available.
<TextBox x:Name="PART_TextBox"
Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Value}"
Margin="0,0,1,0"
TextAlignment="Right"
AcceptsReturn="False"
SpellCheck.IsEnabled="False"
HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Center"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
MaxWidth="{Binding ElementName=TBMeasure, Path=ActualWidth}"
/>
<!-- Hidden measuring textbox ensures reservation of enough UI space
according to DisplayLength dependency property
-->
<TextBox x:Name="TBMeasure"
Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=DisplayLength, Converter={StaticResource ByteToPlaceHolderStringConverter}}"
Margin="0,0,1,0"
TextAlignment="Right"
AcceptsReturn="False"
SpellCheck.IsEnabled="False"
HorizontalContentAlignment="Right"
VerticalContentAlignment="Center"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Visibility="Hidden"/>
// Converter
[ValueConversion(typeof(byte), typeof(string))]
public sealed class ByteToPlaceHolderStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((value is byte) == false)
return Binding.DoNothing;
byte byteVal = (byte)value;
string retString = string.Empty;
for (int i = 0; i < byteVal; i++)
retString = retString + "X";
return retString;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Binding.DoNothing;
}
}

ItemsControl, VirtualizingStackPanel and ScrollViewer height

I want to display a important list of items using an ItemsControl.
The reason why I'm using an ItemsControl is that the DataTemplate is much more complex in the application I'm working on: The sample code provided only reflects the sizing problem I have.
I would like :
the ItemsControl to be virtualized because there is many items to display
its size to expand to its parent container automatically (the Grid)
<Grid>
<ItemsControl x:Name="My" ItemsSource="{Binding Path=Names}">
<ItemsControl.Template>
<ControlTemplate>
<StackPanel>
<StackPanel>
<TextBlock Text="this is a title" FontSize="15" />
<TextBlock Text="This is a description" />
</StackPanel>
<ScrollViewer CanContentScroll="True" Height="400px">
<VirtualizingStackPanel IsItemsHost="True" />
</ScrollViewer>
</StackPanel>
</ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
The code behind is :
public partial class Page1: Page
{
public List<string> Names { get; set; }
public Page1()
{
InitializeComponent();
Names = new List<string>();
for(int i = 0; i < 10000; i++)
Names.Add("Name : " + i);
My.DataContext = this;
}
}
As I force the ScrollViewer height to 400px, ItemsControl virtualization works as I expect: The ItemsControl displays the list very quickly, regardless of how many items it contains.
However, if I remove Height="400px", the list will expand its height to display the whole list, regardless its parent container height. Worse: it appears behind its container.
Putting a scrollviewer around the ItemsControl gives the expected visual result, but the virtualization goes away and the list takes too much time to display.
How can I achieve both automatic height expansion and virtualization of my ItemsControl ?
The problem is in the ItemsControl.Template: you use StackPanel there, which gives her children as much height as they want. Replace it to something like
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel>
<TextBlock Text="this is a title" FontSize="15" />
<TextBlock Text="This is a description" />
</StackPanel>
<ScrollViewer CanContentScroll="True" Grid.Row="1">
<VirtualizingStackPanel />
</ScrollViewer>
</Grid>
And it should work fine.
Hope it helps.

Resources