2011-08-18 103 views
6

我有一个wpf窗口,里面有两个usercontrols,其中第二个只在需要时显示。我只在XAML中设置窗口的MinWidth,通过数据绑定提供MinHeight,取决于是否显示第二个用户控件。现在:如何在运行期间将窗口大小设置为不同于MinWidth/Height的值。我尝试在Show()之前,Show()之后,各种事件(Initialized,Loaded等)中设置值。我尝试使用和不使用UpdateLayout(),我尝试通过数据绑定设置高度/宽度。没有用!但是,当我调试的方法,我看到窗口的高度/宽度属性设置为预期值,但实际高度/宽度保持不变。我认为这将是一个小品,但事实证明它不是(对我来说)。你有任何帮助。用c编程调整wpf窗口的大小#

+0

这听起来有点不可思议。窗户应该尊重您的宽度和高度设置。你可以发布一个最简单的例子吗? – Jens

+0

是否有可能将'Window.SizeToContent'设置为'Manual'以外的其他值?如果是这样,'Width'和/或'Height'将有效地从'ActualWidth'和'AcutalHeight'解耦。 – dlf

回答

8

你试过设置

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> 

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

1

你没有给出太多的信息,所以我只是在这里猜测。

当我将SizeToContent设置为WidthAndHeight时,我可以重现不符合宽度和高度设置的窗口的唯一方法是将SizeToContent设置为WidthAndHeight

1

,如果有人还在为此挣扎,你所要做的唯一事情是这样的:

如果要调整主窗口中只写了下面的代码。

Application.Current.MainWindow.Height = 420; 

如果你想调整除主窗口之外的新窗口只写在新窗口中的cs文件下面的代码。

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

希望它有帮助。