C#开发学习笔记:WPF使用ViewBox使控件随WinForm窗体的大小改变自适应大小

时间:2024-03-15 20:52:22

使用ViewBox嵌套控件

<UserControl x:Class="DemoCollection.WPFUserControl2"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Viewbox x:Name="Viewbox" >
            <Button x:Name="Button" Content="控件大小随窗体自适应测试" VerticalAlignment="Top" HorizontalAlignment="Left" />
        </Viewbox>
    </Grid>
</UserControl>

然后设置ViewBox的Width和Height属性为自适应

C#开发学习笔记:WPF使用ViewBox使控件随WinForm窗体的大小改变自适应大小

 

ViewBox的Child属性只能设置一次(也就是只能有一个子控件),因此如果有多个控件,可以其他容器控件包含如再加一个Grid

<UserControl x:Class="DemoCollection.WPFUserControl2"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Viewbox x:Name="Viewbox" >
            <Grid >
                <Button x:Name="Button" Content="控件大小随窗体自适应测试1" VerticalAlignment="Top" HorizontalAlignment="Left" />
                <Button x:Name="Button2" Content="控件大小随窗体自适应测试2" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="0,19,0,-19" />
            </Grid>
        </Viewbox>
    </Grid>
</UserControl>