无法将动画应用于页面 WPF c# 中的父框架

Cannot apply animation to parent frame from page WPF c#

我在 Frame 中有一个 page。我想做的是将 storyboard/animation 从页面应用到父 Frame。通常,从用户控件中,我使用以下代码获取父级:

var parent = (Frame)this.Parent;

但是如果我在我的页面中使用相同的代码来获取父框架并应用动画:

private void Goback_MouseDown(object sender, MouseButtonEventArgs e)
{
Storyboard sb = new Storyboard;
sb = this.FindResource("HideMainframe");
var parent = (Frame)this.Parent;
Storyboard.SetTarget(sb, parent);
sb.Begin();
}

故事板

 <Storyboard x:Key="HideMainframe" Storyboard.TargetProperty="Opacity" >
        <DoubleAnimation Duration="0:0:0.5" To="0" >
            <DoubleAnimation.EasingFunction>
                <CircleEase  EasingMode="EaseIn"/>
            </DoubleAnimation.EasingFunction>
        </DoubleAnimation>
    </Storyboard>

我得到一个例外:No target was specified for 'System.Windows.Media.Animation.DoubleAnimation'.。在网络上,我开始了解 VisualTreeHelper class 但在我去做之前,我想知道,为什么我的代码不工作?或者具体来说,为什么我不能从页面中获取父框架?

所以看起来在框架中导航的页面不包含 "Parent" 值,这就是为什么您指定的方法不起作用,但遍历 VisualTreeHelper 却起作用的原因。通过将 Frame 传递给 Page 构造函数,可以轻松简化您想要实现的目标。

您的页面代码隐藏

Frame f;
public Page1(Frame frame)
{
    f = frame;
    InitializeComponent();
}

你的按钮逻辑

private void Goback_MouseDown(object sender, MouseButtonEventArgs e)
{
   Storyboard sb = (Storyboard)this.TryFindResource("HideMainframe");
   Storyboard.SetTarget(sb, f);
   sb.Begin();
}

因此,在浏览框架时,您只需通过它即可。

myFrame.Navigate(new Page1(myFrame));