在代码中动态设置网格宽度

时间:2017-04-27 14:42:29

标签: c# uwp

我有一个包含此列的网格:

    <Grid.ColumnDefinitions>
        <ColumnDefinition x:Name="FirstColumn" Width="*" />
        <ColumnDefinition x:Name="SecondColumn" Width="Auto"/>
    </Grid.ColumnDefinitions>

按下按钮后,我希望第二列扩展为2 *。我怎样才能做到这一点?我尝试了这个,但它抛出了一个异常 - 发生了'System.Runtime.InteropServices.COMException'类型的异常:(

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var sb = new Storyboard();
        var animation = new DoubleAnimation()
        {
            To = new GridLength(2, GridUnitType.Star).Value,
            From = SecondColumn.ActualWidth,
            EnableDependentAnimation = true
        };
        Storyboard.SetTargetProperty(animation, "Width");
        Storyboard.SetTarget(animation, SecondColumn);
        sb.Children.Add(animation);

        sb.Begin();
    }
编辑:我用这种方式编辑了代码:

        var sb = new Storyboard();
        var animation = new ObjectAnimationUsingKeyFrames
        {
            BeginTime = TimeSpan.FromSeconds(0)
        };
        Storyboard.SetTarget(animation, SecondColumn);
        Storyboard.SetTargetProperty(animation, "Width");
        var keyFrame = new DiscreteObjectKeyFrame
        {
            KeyTime = TimeSpan.FromSeconds(2),
            Value = new GridLength(2, GridUnitType.Star)
        };
        animation.KeyFrames.Add(keyFrame);
        sb.Children.Add(animation);
        sb.Begin();

但是动画不是连续的,它只是等待2秒然后跳到那里。我怎样才能连续不断?

1 个答案:

答案 0 :(得分:0)

DoubleAnimation.ToDouble类型,我们无法将GridLength设置为Double类型。

正如lindexi所说,我们可以将GridLength设置为ColumnDefinition.Width

  

ColumnDefinition和RowDefinition等类型对其某些属性使用GridLength值(ColumnDefinition.Width和RowDefinition.Height)。这些属性值用于支持布局容器(如Grid)中的可用空间的可变分布(以及Grid的派生类型,如VariableSizedWrapGrid)。 GridLength可以描述三种调整模式中的一种:固定宽度,加权分布(星形大小)或“自动”大小调整模式。

如需了解更多信息,请Grid​Length Struct

如果您想将星号用于宽度,我们应该可以将GridUnitType.Star设置为GridLength

例如:

private void Button_Click(object sender, RoutedEventArgs e)
{
    SecondColumn.Width = new GridLength(2, GridUnitType.Star);
}

如果您想使用DoubleAnimation,您应该能够获得窗口的宽度并将您想要的宽度设置为DoubleAnimation.To

相关问题