2014-04-21 24 views
2

是我的代碼,窗口高度雙向綁定問題下面

public partial class MainWindow : Window, INotifyPropertyChanged 
    { 
     private int myHeight = 0; 

     public int MyHeight 
     { 
      get { return myHeight; } 
      set 
      { 
       myHeight = value; 
       OnPropertyChanged("MyHeight"); 
       MessageBox.Show("MainWindowHeight" + MyHeight); 
      } 
     } 

     public MainWindow() 
     { 
      InitializeComponent(); 
      this.DataContext = this; 
     } 
     private void OnPropertyChanged(string prop) 
     { 
      if (PropertyChanged != null) 
      { 
       PropertyChanged(this, new PropertyChangedEventArgs(prop)); 
      } 
     } 
     public event PropertyChangedEventHandler PropertyChanged; 
    } 

<Window x:Class="Window_Sample.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="{Binding MyHeight, Mode=TwoWay}" Width="525"> 

    <Grid> 

    </Grid> 
</Window> 

當我改變從最小到最大的setter我的WindowState被調用兩次,第一次有正確的實際值,並在第二叫它有價值38,有沒有這種行爲的任何解釋?還有它爲什麼會被叫兩次?

感謝, 庫馬爾

回答

4

如果你看一下訪問該屬性,你會看到第二個經過一個函數調用UpdateDimensionsToRestoreBounds的兩次調用堆棧。這樣做對這個網絡搜索導致我在這裏

http://referencesource.microsoft.com/#PresentationFramework/src/Framework/System/Windows/Window.cs#c8ff58cc4568752a

此功能的評論說,當最大化或最小化窗口的意圖是讓物業持有的價值沒有最大化或最小化時。看起來這是兩次調用的原因,第二次是設置未被最大化或最小化時的值。

如果你想知道窗口的高度,你可以使用

double renderedHeight = Application.Current.MainWindow.ActualHeight; 

希望這有助於