2010-07-19 120 views
2

我想通過我的ViewModel控制我的一個窗口的高度和寬度。wpf窗口寬度沒有約束

這似乎很簡單。

<Window ... Width="{Binding Path=Width}" Height="{Binding Path=Height}" /> 

但沒有。它不起作用。

它檢查ViewModel的Width而不是Height

奇怪的是,如果切換在XAML的WidthHeight順序它檢查Height而不是Width。即它只檢查兩個屬性中的第一個,完全忽略第二個屬性。

綁定MaxHeightMinHeight做功,即使在Width之後。但是,用戶無法重新調整窗口的大小。

回答

0

我也有這個確切的問題,它看起來像一個錯誤。

現在我只是處理窗口的DataContextChanged事件,並手動設置ViewModel的寬度和高度。

+0

謝謝 - 這個評論似乎是唯一適用於我的想法,但我仍然認爲我們應該能夠改變綁定的屬性並查看UI中反映的結果。任何人都可以正確地使用它。 – Chris 2014-10-16 22:23:13

2

不知道您的視圖模型的代碼是什麼樣子,但嘗試創造的寬度和高度的屬性一組,並設置綁定模式爲雙向

0

這是由設計(可悲的,但真正的)正確。佈局系統實際上並沒有強制執行這些值,請參閱msdn文檔頁面上有關Window.Height的註釋... 在某些情況下,可以將MinWidth和MaxWidth(resp。* Height)設置爲實現類似的行爲,但不總是。

對不起,有沒有更好的消息...

+0

哦,還請參見[this other thread](http://stackoverflow.com/questions/4806088/wpf-finding-position-of-maximized-window/6525577#6525577) – eFloh 2011-06-29 18:42:48

1

,你應該在你的窗口的Load事件是這樣的:

public void AfterLoad() 
    { 
     this.Height = this.ViewModel.Settings.WindowHeight; 
     this.Width = this.ViewModel.Settings.WindowWidth; 

     if (this.ViewModel.Settings.WindowTop > 0 && this.ViewModel.Settings.WindowLeft > 0) 
     { 
      this.Top = this.ViewModel.Settings.WindowTop; 
      this.Left = this.ViewModel.Settings.WindowLeft; 
     } 
    } 

然後,處理窗口的大小改變事件記住widht和高度並且位置也改變爲記住頂部,左側(如果你願意的話)。

綁定到WindowState工作正常。

+0

正確。只需在Settings.Default.WindowHeight中添加「Default」即可。 – fab 2012-04-27 15:15:38

0

你想綁定到ActualHeight和ActualWidth,而不是高度和寬度。

所以不是:

<Window ... Width="{Binding Path=Width}" Height="{Binding Path=Height}" /> 

你想:

<Window ... Width="{Binding Path=ActualWidth}" Height="{Binding Path=ActualHeight}" /> 
0

我假設你正在使用MVVM模式與提高任何改變propertys從視圖模型到視圖的常用方法,通過在ViewModel中實現INotifiyPropertyChanged接口。

不工作:

WdwWidth = 600; 
WdwHeight = 600; 

RaisePropertyChanged("WdwWidth"); 
RaisePropertyChanged("WdwHeight"); 

工作:

WdwWidth = 600; 
RaisePropertyChanged("WdwWidth"); 

WdwHeight = 600; 
RaisePropertyChanged("WdwHeight"); 

在我看來,該PropertysChanged通知還有待提高之後的財產實際上已經改變了。奇怪的,但對我來說是訣竅。

編輯:確保將Binding設置爲TwoWay,例如, Height="{Binding Path=WdwHeight, Mode=TwoWay}"