Binding issue ActualWidth on dynamic filled Grid

萝らか妹 提交于 2019-12-04 18:03:31

The main problem is that ActualWidth of a ColumnDefinition isn't a Dependency Property, nor does it implement INotifyPropertyChanged so the Binding has no way of knowing that the ActualWidth of coltest has changed.

You'll need to explicitly update the Binding

Edit2: In this case, you might be able to update the Binding in the SizeChanged event for the Grid since the Columns have * width. This won't work 100% with Auto width though since the width will change based on the elements in the ColumnDefinition

<Grid Name="grid"
      SizeChanged="grid_SizeChanged">
    <!--...-->
</Grid>

Event handler

void grid_SizeChanged(object sender, SizeChangedEventArgs e)
{
    BindingExpression be = label.GetBindingExpression(Label.ContentProperty);
    be.UpdateTarget();
}

Edit: Made some small changes to the Xaml. This will update the Binding everytime you doubleclick the first Label

<Grid Name="grid">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="162*" />
        <ColumnDefinition x:Name="coltest" Width="316*" />
        <ColumnDefinition Width="239*" />
        <ColumnDefinition Width="239*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <Label MouseDoubleClick="TextBox_MouseDoubleClick"
           Name="label"
           Content="{Binding ElementName=coltest, Path=ActualWidth}" Grid.Row="0"/>
</Grid>

Event handler

private void TextBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    grid.RowDefinitions.Add(new RowDefinition());
    for (int i = 0; i < grid.ColumnDefinitions.Count; i++)
    {
        Random r = new Random();
        Label l = new Label { Content = r.Next(10, 1000000000).ToString() };
        grid.Children.Add(l);
        Grid.SetRow(l, grid.RowDefinitions.Count - 1);
        Grid.SetColumn(l, i);
    }
    BindingExpression be = label.GetBindingExpression(Label.ContentProperty);
    be.UpdateTarget();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!