在c#中以编程方式调整wpf窗口大小

时间:2011-08-18 06:17:39

标签: c# wpf xaml resize

我有一个带有两个用户控件的wpf窗口,其中第二个只在需要时显示。我只在XAML中设置窗口的MinWidth,MinHeight是通过数据绑定提供的,具体取决于是否显示第二个用户控件。现在:如何在运行时将窗口大小设置为与MinWidth / Height不同的值。我尝试在Show()之后的Show()之前设置各种事件(Initialized,Loaded等)中的值。我尝试使用和不使用UpdateLayout(),我尝试通过数据绑定设置高度/宽度。什么都行不通!但是,当我调试方法时,我看到窗口的高度/宽度属性设置为预期值,但ActualHeight / Width保持不变。我认为这将是一个小包,但事实证明它不是(对我而言)。求你帮忙。

4 个答案:

答案 0 :(得分:9)

您是否尝试过设置

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>

单击按钮设置窗口高度。那是你在找什么?

答案 1 :(得分:3)

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

当我将SizeToContent设置为WidthAndHeight时,我唯一能够重现窗口而不考虑其宽度和高度设置的方法。

答案 2 :(得分:3)

如果有人仍在努力解决这个问题,你唯一需要做的就是:

如果要调整主窗口的大小,只需编写以下代码。

Application.Current.MainWindow.Height = 420;

如果要调整主窗口以外的新窗口,只需在新窗口的.cs文件中编写以下代码。

Application.Current.MainWindow = this; 
Application.Current.MainWindow.Width = 420;

希望它有所帮助。

答案 3 :(得分:0)

我只是简单地设置窗口的Height属性。

最初为_myWindow.Height = 400;

一旦内容需要调整大小,我将其设置如下:

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

_myWindow.Height = newWindowHeight;

相关问题