【问题标题】:Member 'Storyboard.SetTargetName(DependencyObject, string)' cannot be accessed with an instance reference; qualify it with a type name instead无法使用实例引用访问成员“Storyboard.SetTargetName(DependencyObject, string)”;改为使用类型名称来限定它
【发布时间】:2020-03-25 17:26:12
【问题描述】:

我正在尝试为我的 WPF 应用程序制作启动动画。我收到以下消息:

error

这是我当前的代码: code

【问题讨论】:

标签: c# wpf


【解决方案1】:

我认为你可以使用这样的代码

Storyboard.SetTargetName(startupAnimation1da, loadingWindow.Name);

代替

startupAnimation1.SetTargetName(startupAnimation1da, loadingWindow.Name);

另外,我认为您的代码不会正确运行,我认为它不会做动画。因为您创建了DoubleAnimation,但没有设置它需要更改的目标属性。您可以使用Storyboard.SetTargetProperty() 方法来设置它:

Storyboard.SetTargetProperty(ANIMATION, PROPERTY);

还有一个例子:

Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath(Button.WidthProperty));

下面是使用Storyboard.SetTargetName()Storyboard.SetTargetProperty() 方法的示例。

这是一个改变按钮宽度的动画。

Xaml:

<Window x:Class="WpfTestApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Button x:Name="AnimationButton" Height="34" Width="100" Content="Begin" Click="AnimationButton_Click"></Button>
</Window>

C#:

using System;
using System.Windows;
using System.Windows.Media.Animation;
using System.Windows.Controls;

namespace WpfTestApp
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void AnimationButton_Click(object sender, RoutedEventArgs e)
        {
            //Create the animaton
            Storyboard storyboard = new Storyboard();

            DoubleAnimation doubleAnimation = new DoubleAnimation
            {
                From = 100,
                To = 300,
                Duration = new Duration(new TimeSpan(0, 0, 1)),
                AutoReverse = true,
                RepeatBehavior = RepeatBehavior.Forever
            };

            storyboard.Children.Add(doubleAnimation);

            //Set taeget name
            Storyboard.SetTargetName(doubleAnimation, "AnimationButton");

            //Set target property
            Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath(Button.WidthProperty));

            //Begin the animaton
            storyboard.Begin(AnimationButton);
        }
    }
}

【讨论】:

  • @HankStudios,你可以试试代码Storyboard.SetTargetName(startupAnimation1da, loadingWindow.Name);,行吗?
猜你喜欢
  • 1970-01-01
  • 2023-04-08
  • 2015-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多