如何在通用平台中绑定网格ColumnDefinition.Width?

时间:2018-08-03 14:08:24

标签: uwp uwp-xaml

对不起,我没有找到答案。

<Grid x:Name="MyGrid" Background="LightGray" >
  <Grid.ColumnDefinitions >
    <ColumnDefinition MaxWidth="30"/>
    <ColumnDefinition Width="{Binding Column1 , Mode=TwoWay}"/>
    <ColumnDefinition MaxWidth="30"/>
  </Grid.ColumnDefinitions>
  <Grid Grid.Column="0">
    <TextBox Text="0"/>
  </Grid>
  <Grid Grid.Column="1">
    <TextBox Text="1"/>
  </Grid>
  <Grid Grid.Column="2">
    <TextBox Text="2"/>
  </Grid>
</Grid>

后面的代码:

public sealed partial class MainPage : Page
{
  private GridLength _column1 = new GridLength(10);
  public GridLength Column1
  {
    get
    {
      return _column1;
    }
    set
    {
     _column1 = value;
    }
  }

  public MainPage()
  {
    this.InitializeComponent();
  }
}

此代码有什么问题? 顺便说一句,是否可以在xaml中保留Grid.ColumnDefinitions部分并直接为column设置ColumnDefinition属性(不要在后面的代码中为每个属性设置变量)

1 个答案:

答案 0 :(得分:1)

Binding使用 DataContext 作为默认源,如果要在页面中的代码后面绑定Column1属性,则应指定此页面的数据上下文,因此只需将以下代码添加到MainPage的构造函数中即可。

public MainPage()
{
    this.InitializeComponent();
    //Add this code to specify the binding's data context
    this.DataContext = this;
}

---更新---

通常,我们使用Binding绑定数据模型的属性,如果您想通过更改后面代码中的某些参数来更改列/网格值,则可以实现INotifyPropertyChanged接口并使该属性订阅PropertyChanged事件,这是一个基于您上面的代码的简单代码示例,

在xaml中,我添加了一个Button,以更改其click事件中的Column1属性,

<Grid x:Name="MyGrid" Background="LightGray" >
    <Grid.ColumnDefinitions >
        <ColumnDefinition x:Name="Column0" MaxWidth="30"/>
        <ColumnDefinition Width="{Binding Column1 , Mode=TwoWay}"/>
        <ColumnDefinition MaxWidth="30"/>
    </Grid.ColumnDefinitions>
    <Grid Grid.Column="0">
        <TextBox Text="0"/>
        <Button Content="click me to change the Column 1's width" Click="Button_Click"/>
    </Grid>
    <Grid Grid.Column="1">
        <TextBox Text="1"/>
    </Grid>
    <Grid Grid.Column="2">
        <TextBox Text="2"/>
    </Grid>
</Grid>

这是实现INotifyPropertyChanged接口的背后代码。

public sealed partial class MainPage: Page, INotifyPropertyChanged
{

    private GridLength _column1 = new GridLength(20);

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string PropertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
        }
    }

    public GridLength Column1
    {
        get
        {
            return _column1;
        }
        set
        {
            _column1 = value;
            OnPropertyChanged("Column1");
        }
    }
    public MainPage()
    {
        this.InitializeComponent();
        //Add this code to specify the binding's data context
        this.DataContext = this;
    }

    Double width = 20;
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Column1 = new GridLength(width += 10);
    }
}