做客户端有时为了让界面适用各种不同的系统分辨率,让界面内控件布局大小始终保存比例是一种方法。一般可以使用配置文件做不同分辨率的适配实现,或者通过代码根据不同的分辨率重新计算控件大小及位置实现。在wpf有一种更简单的方法,使用viewbox。
ViewBox可以自动缩放其内部的元素,无论是控件、容器、文本都可以按比例自动缩放。想要实现整个窗口按比例缩放需要如下步骤:
标签下第一个元素代码如下:
下面代码中,窗口是按照1920x1080设计的,但实际的窗口只有640x360,但其显示的效果控件比例始终是一样的。
<Window x:Class="WpfApp1.MainWindow"
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"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="360" Width="640">
<Viewbox>
<Grid Width="1920" Height="1080">
<Border CornerRadius="20" Width="1280" Height="720" Background="#666666">Border>
Grid>
Viewbox>
Window>
上述代码的显示效果如下