使silverlight适应IE窗口大小的方法

    Pete Brown在它的BLOG中提到了一个按自定义比例使用silverlight适应IE窗口大小的方法

    原文如下:How to Resize a Silverlight 2 App and Keep the Same Aspect Ratio                

    其核心代码如下(
Xaml):

复制代码
<UserControl x:Class="PeteBrown.SilverlightScalingExample.Page"
    xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
    
>
   
    
<Grid x:Name="LayoutRoot"
          Background
="Cornsilk" ShowGridLines="True"
          Width
="400" Height="300"
          RenderTransformOrigin
="0.5 0.5">
       
        
<Grid.RenderTransform>
            
<ScaleTransform x:Name="PageScale" ScaleX="1" ScaleY="1"/>
        
</Grid.RenderTransform>
       

    
</Grid>
</UserControl>
复制代码



复制代码
public partial class Page : UserControl
{
    
// this is the aspect ratio we want to maintain
    
// you can specify this all sorts of ways, but the
    
// easiest is to take the original size and divide
    
// X by Y (4:3 or 1.333 in this case)
    private const double _originalWidth = 400;
    
private const double _originalHeight = 300;
    
private const double _originalAspectRatio =
        _originalWidth 
/ _originalHeight;

    
public Page()
    {
        InitializeComponent();

        
// wire up the event handler. This is a great addition
        
// to silverlight, as you used to have to hook into the
        
// browser event yourself
        SizeChanged += new SizeChangedEventHandler(Page_SizeChanged);
    }

    
void Page_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        
if (e.NewSize.Width < _originalWidth ||
            e.NewSize.Height 
< _originalHeight)
        {
            
// don't shrink
            PageScale.ScaleX = 1.0;
            PageScale.ScaleY 
= 1.0;
        }
        
else
        {
            
// resize keeping aspect ratio the same
            if (e.NewSize.Width / e.NewSize.Height > _originalAspectRatio)
            {
                
// height is our constraining property
                PageScale.ScaleY = e.NewSize.Height / _originalHeight;
                PageScale.ScaleX 
= PageScale.ScaleY;
            }
            
else
            {
                
// either width is our constraining property, or the user
                
// managed to nail our aspect ratio perfectly.
                PageScale.ScaleX = e.NewSize.Width / _originalWidth;
                PageScale.ScaleY 
= PageScale.ScaleX;
            }
        }
    }
}
复制代码


    这是一个很有用的小技巧,所以在这里做一个记号,看看将来是否能用得上:)
posted @   代震军  阅读(2341)  评论(2编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示