主窗口高度宽度将根据当前视图WPF设置

本文关键字:视图 WPF 设置 高度 窗口 | 更新日期: 2023-09-27 18:04:18

我有一个与WPF MVVM相关的问题-我希望主窗口的高度和宽度将根据当前视图的高度'宽度设置。

我如何定义它?

MainWindow.xaml

    <Window x:Class="Project.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:Project"
        xmlns:views ="clr-namespace:Project.Views"
        mc:Ignorable="d"
        Title="MainWindow" 
        Height="{Binding Source = {x:Static SystemParameters.PrimaryScreenHeight}, Converter={local:RatioConverter}, ConverterParameter='0.6'}"  
        Width="{Binding Source={x:Static SystemParameters.PrimaryScreenWidth}, Converter={local:RatioConverter}, ConverterParameter='0.5'}"
        >
    <Grid>
        <ContentControl Name="placeholder"></ContentControl>
    </Grid>
</Window>

在其中一个视图

 <UserControl x:Class="Project.Views.MsgBox"
             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" 
             xmlns:local="clr-namespace:Project.Views"
             mc:Ignorable="d" 
>
    <UserControl.Background>
        <SolidColorBrush Color="#000000" Opacity="0.5"  />
    </UserControl.Background>
    <Grid Opacity="1" >
        <Grid Width="360"   Background="White" Opacity="1" Margin="0,0,0,0" VerticalAlignment="Center" HorizontalAlignment="Center">
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="*" />
                <RowDefinition MinHeight="90" Height="auto"/>
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>
    ... any code...
    </Grid>
</UserControl>

主窗口高度宽度将根据当前视图WPF设置

如果您希望Window具有与其内容相同的大小,则将SizeToContent属性设置为WidthAndHeight:

<Window  ...  SizeToContent="WidthAndHeight">
    <Grid>
        <ContentControl Name="placeholder"></ContentControl>
    </Grid>
</Window>