1. 程式人生 > >wpf自適應螢幕解析度:viewbox控制元件的使用方法

wpf自適應螢幕解析度:viewbox控制元件的使用方法

 

使用View Box:在固定長寬的canvas/grid外新增viewbox控制元件,視窗大小或者解析度改變,裡面的控制元件和字型大小都會自適應改變。

<Window x:Class="WpfTest2.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:WpfTest2"
        mc:Ignorable="d"
        Title="MainWindow" WindowState="Maximized">
    <Viewbox>
        <Grid Width="1920" Height="1080">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="400"></ColumnDefinition>
                <ColumnDefinition Width="*"></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="400"></RowDefinition>
                <RowDefinition Height="*"></RowDefinition>
            </Grid.RowDefinitions>
            <Button Margin="20" Content="左上" FontSize="50" Grid.Column="0" Grid.Row="0"></Button>
            <Button Margin="20" Content="右上" FontSize="50"  Grid.Column="1" Grid.Row="0"></Button>
            <Button Margin="20" Content="下" FontSize="50"   Grid.Column="0"  Grid.ColumnSpan="2" Grid.Row="1" ></Button>
        </Grid>
    </Viewbox>
</Window>

執行後,可以拖拽或者改變電腦解析度試試效果、

注:如果一開始沒有設定最大化,視窗一般不會自適應,需要按比例拖拽才會看到效果