【问题标题】:Set control Height as other control's height but add extra height将控件高度设置为其他控件的高度,但添加额外的高度
【发布时间】:2017-08-31 17:55:42
【问题描述】:

我有一个故事板,当按下 ToggleButton 但 Grid 的高度是硬编码时,我可以使用它来更改 Grid 的大小。如何根据其他元素设置其高度,但还要为其添加额外的像素?更具体地说,我希望 Grid 在折叠时为 50pt,但在展开时应为 50pt+另一个元素的高度(将显示在 Grid 中的额外空间中)。

<Style TargetType="{x:Type Grid}" x:Key="ExpandCollapseTopBar">
    <Style.Triggers>
        <EventTrigger RoutedEvent="ToggleButton.Checked">
            <EventTrigger.Actions>
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetProperty="(Grid.Height)" From="50.0" To="100.0" Duration="0:0:0.1"/>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger.Actions>
        </EventTrigger>
        <EventTrigger RoutedEvent="ToggleButton.Unchecked">
            <EventTrigger.Actions>
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetProperty="(Grid.Height)" From="100.0" To="50.0" Duration="0:0:0.1"/>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger.Actions>
        </EventTrigger>
    </Style.Triggers>
</Style>

我会使用绑定到另一个元素的高度,但我无法添加额外的像素。

Height="{Binding ElementName=TheOtherElement, Path=ActualHeight}"

【问题讨论】:

  • 您可以定义一个转换器以应用于您的绑定:Height="{Binding ElementName=TheOtherElement, Path=ActualHeight, Converter={StaticResource YourConverter}" 然后将这些 50px 添加到转换器中。
  • 该死,在情节提要属性中使用绑定似乎会使应用程序崩溃
  • 是的:stackoverflow.com/questions/2186933/…。这就是为什么您应该按照我在回答中的建议以编程方式应用动画的另一个原因。

标签: wpf xaml


【解决方案1】:

通过为Grid 处理ToggleButton.CheckedToggleButton.UnChecked 事件以编程方式应用动画:

private void Grid_Checked(object sender, RoutedEventArgs e)
{
    Storyboard sb = new Storyboard();
    double height = 100; //set whatever height you want here
    DoubleAnimation animation = new DoubleAnimation() { From = 50.0, To = height, Duration = TimeSpan.FromSeconds(1) };
    Storyboard.SetTargetProperty(animation, new PropertyPath("(Grid.Height)"));
    Storyboard.SetTarget(animation, sender as Grid);
    sb.Children.Add(animation);
    sb.Begin();
}

然后您可以根据需要计算高度。您不能在 XAML 等 标记 语言中执行此操作。

这不会以任何方式破坏 MVVM。 MVVM 不是关于从视图中消除与视图相关的代码。这是关于关注点分离。

【讨论】:

  • 有没有办法只添加Height="{Binding ElementName=TheOtherElement, Path=ActualHeight}"?这将是一个快速修复,无需在 C# 中重写它。不幸的是,我看到在 Storyboard 属性中添加此绑定似乎会使应用程序崩溃。我做错了吗?
  • 您通常不能在 Storyboard 中应用绑定,因为它们出于性能原因被冻结。所以不,没有“添加...的方法”。这当然不是一个大的“重写”。
  • 我决定放弃这个想法,只对故事板值进行硬编码,但您的答案似乎最接近我需要实现的目标,因此我将其标记为答案。
【解决方案2】:

您可以使用像 CalcBinding 这样的库来创建绑定标记扩展来执行此操作。

我没有尝试过,但它应该像这样工作:

Height="{calc:Binding ElementName=TheOtherElement, Path=ActualHeight + 50}"

如果您不想依赖外部库,可以使用Converter,它会添加额外的像素。做这么简单的事情,这就是我要遵循的路线。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多