Reputation: 6766
I have a particular layout behavior in mind, and I want to see if anyone can come up with a simple way of doing this before I try to write a custom panel or something. Take a look at this animation I manually put together:
There is an element of fixed width to the far left (the rectangle), and then a second element that is centered- not within the remaining space, but relative to the entire container. As the container shrinks, the centered element stays centered until the left element gets too close. Instead of staying directly in the middle, the "centered" element now stays as close to the center as possible without overlapping. This is the behavior I want.
Using a Grid
, I can do something like this:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Border Width="100" Background="Green"/>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Grid.ColumnSpan="2" FontSize="24" Margin="2, 0">Centered Text</TextBlock>
</Grid>
Which puts everything in the right place, but the TextBlock
will start overlapping with the Border
instead of moving further right.
So any idea how I can get this to do what I want?
Upvotes: 1
Views: 171
Reputation: 510
Give this a try:
Name of Window x:Name="window1"
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Border x:Name="border1" Width="100" Background="Green"/>
<TextBlock x:Name="textBlock1" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="24" Grid.ColumnSpan="2">Centered Text</TextBlock>
</Grid>
SizeChanged event
private void Window1_SizeChanged(object sender, SizeChangedEventArgs e) {
if(( ( window1.Width / 2 ) - ( textBlock1.ActualWidth / 2 ) - border1.Width - ( SystemParameters.ResizeFrameVerticalBorderWidth * 2 ) ) <= 0) {
Grid.SetColumn(textBlock1, 1);
textBlock1.HorizontalAlignment = HorizontalAlignment.Left;
} else {
Grid.SetColumn(textBlock1, 0);
textBlock1.HorizontalAlignment = HorizontalAlignment.Center;
}
}
Upvotes: 2