Reputation: 3274
would like two controls to take up all the available space and be of exact same size. Also, when changing one controls visibility to collapsed I want the other control to take up the space. How is it possible?
The following xaml will make sure the controls are of same height and fill the space. But the space is taken by the two rows regardless of the visibility of the controls.
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Name="t1" Grid.Row="0" Text="first" />
<TextBlock Name="t2" Grid.Row="1" Text="second" />
</Grid>
Any help is much appreciated
Upvotes: 1
Views: 62
Reputation: 4774
If you have small fixed amount of this controls then you can also use alternative solution, which is to bind row height to controls visibility. To do that we can modify your example like this:
<Grid>
<Grid.Resources>
<local:VisibilityToRowHeightConverter x:Key="visibilityToRowHeightConverter" />
</Grid.Resources>
<Grid.RowDefinitions>
<RowDefinition Height="{Binding Visibility, ElementName=t1, Converter={StaticResource visibilityToRowHeightConverter}}" />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Name="t1" Text="first" />
<TextBlock Name="t2" Grid.Row="1" Text="second" />
</Grid>
And the converter code:
public class VisibilityToRowHeightConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is Visibility)
return ((Visibility) value) == Visibility.Visible
? new GridLength(1, GridUnitType.Star)
: new GridLength(0);
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
So every time t1
collapses, corresponding RowDefinition
will set it`s value to 0 and return in to one star when t1
is shown again.
Upvotes: 2
Reputation: 6172
Hard to do with Silverlight stock panels. Think about implementing a StretchPanel
.
About SL StretchPanel
implementations:
SO question and answer and blog post linked from there
Upvotes: 2
Reputation: 102793
I can't think of a way to do what you want, using any of the built-in panel controls.
A simple hack would be to update the number of row definitions each you update the visibility:
int numberOfRows = grid.Children.Count(item => item.Visibility == Visibility.Visible);
grid.RowDefinitions.Clear();
for (int i=0 ; i<numberOfRows ; i++)
grid.RowDefinitions.Add(new RowDefinition());
This will ensure that the visible children share the vertical space equally.
A more robust approach would be to build your own Panel control -- might be worth the effort if you use this kind of layout a lot.
Upvotes: 1