【问题标题】:Get a Framework element from a Storyboard从情节提要中获取框架元素
【发布时间】:2010-11-29 10:20:18
【问题描述】:

我有一个 Storyboard 对象实例的引用,并且想要获取它附加到/动画的框架元素。我还没有想出任何方法来做到这一点。

例如,在下面的 XAML 中,我可以从对情节提要的引用中获取标签或网格

<Grid>
    <Grid.Resources>
        <Storyboard x:Key="myStoryboard">
            <DoubleAnimation Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:5"/>
        </Storyboard>
        <Style x:Key="myStyle" TargetType="{x:Type Label}">
            <Style.Triggers>
                <DataTrigger 
                 Binding="{Binding Path=StartAnimation}" Value="true">
                    <DataTrigger.EnterActions>
                        <BeginStoryboard Storyboard="{StaticResource myStoryboard}" />                            
                    </DataTrigger.EnterActions>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Grid.Resources>
    <Label x:Name="labelHello" Grid.Row="0" Style="{StaticResource myStyle}">Hello</Label>
</Grid>

对于那些想知道为什么我需要这样做的人,这是因为我正在尝试创建一个派生的 Storyboard 类或附加的行为,这将允许我在 DataContext 上指定一个方法名称,以便在 Storyboard 完成时调用事件触发。这将允许我做纯粹的 MVVM,而不是需要一些代码来调用我的视图模型。

【问题讨论】:

    标签: wpf xaml mvvm storyboard frameworkelement


    【解决方案1】:

    如果您将 XAML 更改为以下内容:

    <Grid x:Name="grid">
        <Grid.Resources>
            <Storyboard x:Key="myStoryboard">
                <DoubleAnimation Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:5" Storyboard.Target="{Binding ElementName = grid}"/>
            </Storyboard>
            <Style x:Key="myStyle" TargetType="{x:Type Label}">
                <Style.Triggers>
                    <DataTrigger 
                     Binding="{Binding Path=StartAnimation}" Value="true">
                        <DataTrigger.EnterActions>
                            <BeginStoryboard Storyboard="{StaticResource myStoryboard}" />                            
                        </DataTrigger.EnterActions>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Grid.Resources>
        <Label x:Name="labelHello" Grid.Row="0" Style="{StaticResource myStyle}">Hello</Label>
    </Grid>
    

    这将 x:Name 引入网格,并将 Storyboard.Target 引入 DoubleAnimation。您现在可以使用以下代码获取对网格的引用:

    Storyboard sb = //You mentioned you had a reference to this.
    var timeLine = sb.Children.First();
    var myGrid = Storyboard.GetTarget(timeLine);
    

    【讨论】:

    • 谢谢,它有效!故事板目标应该是 labelHello 以保持行为相同,这意味着我不需要命名网格。在我将其标记为答案之前,将等待并看看是否有人可以在没有 XAML 更改的情况下执行此操作,因为我希望我的附加属性是唯一需要的标记。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-03
    • 2018-07-20
    • 1970-01-01
    相关资源
    最近更新 更多