MainWindow 高度\宽度将根据当前视图 WPF 设置

Posted

技术标签:

【中文标题】MainWindow 高度\\宽度将根据当前视图 WPF 设置【英文标题】:MainWindow height\width will be set according current view WPFMainWindow 高度\宽度将根据当前视图 WPF 设置 【发布时间】:2016-08-28 11:42:50 【问题描述】:

我有一个与 WPF MVVM 相关的问题 - 我希望 MainWindow 的高度和宽度将根据当前视图高度\宽度进行设置。

我该如何定义它?

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>

【问题讨论】:

【参考方案1】:

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

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

【讨论】:

以上是关于MainWindow 高度\宽度将根据当前视图 WPF 设置的主要内容,如果未能解决你的问题,请参考以下文章

Interface Builder 中的自动布局根据外部视图的宽度/高度更改布局

如何根据swift 4或5中的图像大小使图像视图高度和宽度(纵横比)动态? [关闭]

如何根据另一个视图的高度/宽度按比例设置视图高度/宽度?

Qt MainWindow 忽略宽度、高度和标题属性

如何在绘制之前获取调整大小的自定义视图的宽度和高度

在约束布局中根据设备宽度设置视图高度