如何在通用平台绑定Grid ColumnDefinition.Width?

How to bind Grid ColumnDefinition.Width in the Universal Platform?

抱歉,我没有找到答案。

<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 部分并直接为列设置 ColumnDefinition 属性(不要在代码后面为每个 属性 设置变量)

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

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

---更新---

一般我们使用Binding来绑定一个Data model的属性,如果你想通过后面的代码改变一些参数来改变column/Grid的值,你可以实现INotifyPropertyChanged interface and make the property subscribe the PropertyChanged 事件,这是一个基于你上面代码的简单代码示例,

在 xaml 中,我添加了一个 Button 以在其点击事件中更改 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);
    }
}