具有网格高度的Databind Class属性

时间:2013-12-14 01:07:50

标签: c# wpf data-binding

我有以下课程:

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

我想将此字段绑定到网格的第1行高度:

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

我还声明了DataContext:

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

但是根本没有互动。我看不出有什么不对。 非常感谢有人可以解释如何将类属性数据绑定到行Height属性。

2 个答案:

答案 0 :(得分: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; }
}

答案 1 :(得分:1)

绑定仅适用于不包含字段的属性,仅在实现Inotifypropertychanged界面时才更新

所以每当你更新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));
        }
    }

}