let's say I have a grid with 4 columns. Every column takes the same amount of width
-> 100% / 4cols = 25%.
The 3rd column has a TextBlock
or any other control in it. Now, when I resize the Width
of the Window
and the column
gets to a minimum value
, I want the TextBlock
to use ColumnSpan="2"
else the TextBlock
would be too small. I hope you guys understand what I mean. I tried so many things but I didn't even come close to what I want because I'm pretty new to WPF
. For example setting the minWidth
so it doesn't get too small doesn't work because at some point the controls will still be hidden inside the grid column. I don't have any useful xaml
for you, unless you just want the grid layout. Maybe a Grid
is not the right thing i want? The other layouts didn't seem right for this purpose. Any help is appreciated.
You could handle the SizeChanged
event of the Grid
or the window and programmaticlly set the Grid.ColumnSpan
attached property of the TextBlock
whenever the grid/window shrinks below a pre-defined minimum width. Please refer to the following sample code.
private void Grid_SizeChanged(object sender, SizeChangedEventArgs e)
{
const double MinWidth = 200;
Grid grid = (Grid)sender;
if (grid.ActualWidth < MinWidth)
Grid.SetColumnSpan(textBlock, 2);
else
Grid.SetColumnSpan(textBlock, 1);
}
XAML:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="300" Width="300">
<Grid SizeChanged="Grid_SizeChanged">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="25*" />
<ColumnDefinition Width="25*" />
<ColumnDefinition Width="25*" />
<ColumnDefinition Width="25*" />
</Grid.ColumnDefinitions>
<TextBlock Background="Yellow" Text="1" />
<TextBlock Background="Green" Text="2" Grid.Column="1" />
<TextBlock Background="Red" Text="4" Grid.Column="3" />
<TextBlock x:Name="textBlock" Background="Blue" Text="3" Grid.Column="2" Grid.ColumnSpan="2" />
</Grid>
</Window>
If you decrease the width of the window, the blue TextBlock
streches across the third and fourth columns.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.