Auto sizing Silverlight controls

2019-08-28 21:17发布

问题:

I am using Silverlight 4 for a project. I want to know if there is a way I can get the main canvas to stretch to the height and width of the browser window it is hosted in?

I want the controls within to resize in proportion to the main control that hosts all the rest of the controls in the host browser window. This is a Prism application which has a Shell.xaml and a ContentControl within the shell. In this prism case I want the content control to span to 100% of the screen height and width.. and when a Page.xaml loads within it I want the Page's usercontrol to fill up the entire content control of the xaml. Similarly, within the Page.xaml if I have a grid I want the grid to grow to a size no more than a fixed number of pixels

The Grid within the Page.xaml's user control seems to be sizing properly. I am having trouble getting the root user control of the Page.xaml to stretch to the entire width of the browser window. Is there a way this can be done using xaml properties only? I dont want to specify the height and width to 800 and 1200 like I have done below.

This is my code

<UserControl x:Class="MyNamespace.MyClass"
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"
d:DesignHeight="300" d:DesignWidth="400" 
xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
Background="#FF2D8543" 
Height="800" Width="1200"
 >

<Grid x:Name="LayoutRoot" Background="#FFEB0A0A" 
VerticalAlignment="Center" HorizontalAlignment="Center"
Height="Auto" Width="Auto"
 >
</Grid>

Thanks for your time.

回答1:

Yes, use Grid instead of Canvas as top level element. Grid takes all the available space by default.

Learn more about Silverlight layout system here and here.

Update:

Just remove Width and Height attributes from the UserControl:

Height="800" Width="1200"

By setting those explicitly you are giving the control fixed size. If you don't specify Width and Height the control will take all the available space.