在 C# 中以编程方式调整 wpf 窗口的大小 [英] Resizing wpf window programmatically in c#

查看:46
本文介绍了在 C# 中以编程方式调整 wpf 窗口的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有两个用户控件的 wpf 窗口,其中第二个仅在需要时显示.我只在 XAML 中设置了窗口的 MinWidth,MinHeight 是通过数据绑定提供的,根据是否显示第二个用户控件设置了一个列表.现在:如何在运行时将窗口的大小设置为与 MinWidth/Height 不同的值.我尝试在 Show() 之前、Show() 之后、在各种事件(初始化、加载等)中设置值.我尝试使用和不使用 UpdateLayout(),我尝试通过数据绑定设置高度/宽度.没有任何作用!但是当我调试方法时,我看到窗口的高度/宽度属性设置为预期值,但实际高度/宽度保持不变.我以为这会是一个小事,但事实证明它不是(对我来说).你的任何帮助.

I have a wpf window with two usercontrols inside of which the second is only shown when needed. I only set the MinWidth of the window in XAML, the MinHeight is provided through databinding an ist set depending on if the second usercontrol is shown. Now: How can I set the size of the window to different values than the MinWidth/Height during runtime. I tried setting the values before the Show(), after the Show(), in various events (Initialized, Loaded, etc.). I tried with and without UpdateLayout(), I tried setting the Height/Width through databinding. Nothing works! But when I debug the approaches I see that the Height/Width properties of the window are set to the expected values, but ActualHeight/Width stay. I thought it would be a bagatelle but it turned out it is not (to me). Thy for any help.

推荐答案

有没有试过设置

Application.Current.MainWindow.Height = 100;

简短的补充:我只是做了一个简短的测试,在代码中:

Short addition: I just did a short test, in code:

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>

点击按钮设置窗口高度.这就是你要找的吗?

Click on the Button sets the window height. Is that what you´re looking for?

这篇关于在 C# 中以编程方式调整 wpf 窗口的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆