2013-12-14 22 views
1

我有以下類:數據綁定類屬性與網格高度

public class Height 
{ 
    public GridLength GridHeight = new GridLength(200); 
} 

我想這個字段綁定到從網格第一行高:

<Grid.RowDefinitions> 
     <RowDefinition Height="{Binding Path=GridHeight, Mode=OneWay}"></RowDefinition> 
     <RowDefinition></RowDefinition> 
    </Grid.RowDefinitions> 

我也宣佈在DataContext :

public MainWindow() 
    { 
     DataContext = new Height(); 
    } 

但是根本沒有交互。我看不出有什麼不對。 非常感謝,如果有人可以解釋如何將一個類屬性數據綁定到行Height屬性。

回答

1

綁定作品只有只有當你當你更新的GridHeight電網自動更新它的價值

public class Height:INotifyPropertyChanged 
{ 
    GridLength _gridheight = new GridLength(200); 
    public GridLength GridHeight 
      { 
        get{ 
          return _gridheight; 
         } 

        set{ 
          if(_gridheight==value) 
           return; 

          _gridheight=value; 
          NotifyPropertyChanged("GridHeight") 
         } 

     } 

    public event PropertyChangedEventHandler PropertyChanged; 

    private void NotifyPropertyChanged(string propertyName = "") 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 

} 
價值實現INotifyPropertyChanged接口

所以這裏屬性不會領域,和更新

+0

優秀!現在一切都完美無瑕! – LamaCoder

+0

是的,這是WPF的方式! –

2

您需要製作GridHeight屬性,而不是字段。

如果您希望更新Height類,您可能還需要實現INotifyPropertyChanged

public class Height 
{ 
    public Height() 
    { 
     this.GridHeight = new GridLength(200); 
    } 

    // Needs to be a property for data binding 
    public GridLength GridHeight { get; set; } 
} 
+0

非常感謝您提及INotifyPropertyChanged! – LamaCoder