silverlight浏览器自适应问题

今天一个朋友问到我silverlight程序如何占满浏览器窗口,我的第一个反应就是silverlight宿主的宽度和高度没有设置对

View Code
<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
          <param name="source" value="ClientBin/BingMapTest.xap"/>
          <param name="onError" value="onSilverlightError" />
          <param name="background" value="white" />
          <param name="minRuntimeVersion" value="5.0.61118.0" />
          <param name="autoUpgrade" value="true" />
          <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=5.0.61118.0" style="text-decoration:none">
               <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="获取 Microsoft Silverlight" style="border-style:none"/>
          </a>
        </object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;0px;border:0px"></iframe></div>

但是一检查代码,发现silverlight宿主宽度和高度都是设置的100%.那问题是出在xaml页面上了

View Code
<navigation:Page x:Class="BingMapTest.Page1" 
           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"
           xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
           d:DesignWidth="640" d:DesignHeight="480"
           Title="Page1 Page">
    <Grid x:Name="LayoutRoot" Background="Yellow" HorizontalAlignment="Center">
        <Grid.RowDefinitions>
            <RowDefinition Height="0.167*"/>
            <RowDefinition Height="0.5*"/>
            <RowDefinition Height="0.333*"/>
        </Grid.RowDefinitions>
        <Button Content="Button" HorizontalAlignment="Left" Width="187"/>
        <Button Content="Button" Margin="220,1,233,0" Height="70" Grid.Row="1" VerticalAlignment="Top"/>
        <Button Content="Button" HorizontalAlignment="Right" Margin="0,83,52,87" Width="187" Grid.Row="1"/>
        <Button Content="Button" HorizontalAlignment="Right" Margin="0,0,58,0" Width="187" Height="70" Grid.Row="2" VerticalAlignment="Top"/>
    </Grid>
</navigation:Page>

发现xaml页面是用Grid布局的,并且设置了HorizontalAlignment属性,我试着去掉HorizontalAlignment属性,发现变成了全浏览器大小的了.

总结一下,Grid如果不设置大小,那么它将占满包含它的容器.如果这时候设置了HorizontalAlignment,那么Grid的宽度将自动变为它包含的子元素所占的宽度,同理,设置VerticalAlignment属性会引起Grid高度的变化.如果同时设置了HorizontalAlignment和Width属性,那么Grid的宽度将会以Width为准.

原文地址:https://www.cnblogs.com/xiaobaihome/p/2642205.html