2011-08-18 100 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; 

希望它有幫助。