在C#中以编程方式调整WPF窗口大小

10

我有一个WPF窗口,里面包含两个用户控件,第二个用户控件只在需要时显示。我只在XAML中设置了窗口的MinWidth,MinHeight是通过数据绑定提供的,取决于第二个用户控件是否显示。现在问题来了:如何在运行时将窗口大小设置为不同于MinWidth/Height的值。我尝试在Show()之前、之后、在各种事件(Initialized、Loaded等)中设置值。我尝试过使用和不使用UpdateLayout(),我尝试通过数据绑定设置Height/Width。但是什么都不起作用!但是当我调试这些方法时,我看到窗口的Height/Width属性被设置为预期值,但ActualHeight/Width保持不变。我以为这只是小问题,但事实证明它对我来说并不是。感谢任何帮助。


听起来有点奇怪。窗口应该尊重您设置的宽度和高度。您能发布一个最小的示例吗? - Jens
你是否将 Window.SizeToContent 设置为非 Manual 值?如果是,Width 和/或 Height 将与 ActualWidthAcutalHeight 实际上解耦。 - dlf
4个回答

11

你尝试设置过吗?

Application.Current.MainWindow.Height = 100;

简短补充:我刚刚进行了一个简短的测试,代码如下:

public partial class MainWindow : Window, INotifyPropertyChanged
{
    private int _height;
    public int CustomHeight
    {
        get { return _height; }
        set
        {
            if (value != _height)
            {
                _height = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("CustomHeight"));
            }
        }
    }

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
        CustomHeight = 500;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        CustomHeight = 100;
    }
}

还有 XAML:

<Window x:Class="WindowSizeTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="{Binding CustomHeight, Mode=TwoWay}" Width="525">
    <Grid>
        <Button Click="Button_Click">Test</Button>       
    </Grid>
</Window>

点击按钮可以设置窗口的高度。这是你在寻找的吗?


5
如果有人还在为此苦苦挣扎,那么你只需要做以下几件事情:
如果你想要调整主窗口的大小,只需编写下列代码即可。
Application.Current.MainWindow.Height = 420;

如果要调整除主窗口以外的新窗口大小,只需在新窗口的.cs文件中编写以下代码即可。
Application.Current.MainWindow = this; 
Application.Current.MainWindow.Width = 420;

希望这能有所帮助。

5

您没有提供太多信息,所以我只是在猜测。

我发现窗口不遵循其宽度和高度设置的唯一方式是将 SizeToContent 设置为 WidthAndHeight


1

我只是简单地设置了窗口的高度属性。

最初的代码为_myWindow.Height = 400;

一旦内容需要调整大小,我就按照以下方式设置:

double newWindowHeight = a + b; 其中a + b使窗口变大,因此:

_myWindow.Height = newWindowHeight;


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接