如何将XAML内容控件转换为C#中的代码隐藏?

时间:2018-08-02 03:37:54

标签: c# wpf xaml code-behind

所以我在将XAML转换为后面的代码时遇到了一些麻烦。我想创建一个特定的动画,并在这里寻求帮助后,一个用户回答说给我看如何创建我想要的自定义内容控件。他给了我两个文件:Popup.xaml和popup.xaml.cs。理想情况下,我想将所有内容都包含在代码中,但是我对C#和WPF开发是相当陌生的,而且我不确定该怎么做。

以下是XAML文件的内容:

<ContentControl x:Name="ContentControl" 
                x:Class="WpfApplication1.PopupBase"
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                Template="{DynamicResource ContentControlTemplate}"
                Visibility="Hidden">

    <ContentControl.Resources>

        <Duration x:Key="OpenDuration">00:00:00.4</Duration>

        <Storyboard x:Key="OpenStoryboard" Duration="{StaticResource OpenDuration}">
            <DoubleAnimation Storyboard.TargetName="ContentControl" Storyboard.TargetProperty="Opacity" To="1" Duration="{StaticResource OpenDuration}">
                <DoubleAnimation.EasingFunction>
                    <BackEase EasingMode="EaseOut" Amplitude="0.4"/>
                </DoubleAnimation.EasingFunction>
            </DoubleAnimation>
            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentControl" Storyboard.TargetProperty="Visibility" Duration="{StaticResource OpenDuration}">
                <DiscreteObjectKeyFrame Value="{x:Static Visibility.Visible}" KeyTime="00:00:00" />
            </ObjectAnimationUsingKeyFrames>
        </Storyboard>

就xaml.cs文件而言,仅此而已:

var openStoryboard = Resources["OpenStoryboard"] as Storyboard;
openStoryboard.Begin();

到目前为止,我在这里尝试将所有这些都转换为后面的代码:

Duration time = new Duration(new System.TimeSpan(0,0,0,0,400));    

ContentControl cc = new ContentControl
{
    Opacity = 0,
    Visibility = Visibility.Hidden
};

Storyboard openStoryboard = new Storyboard
{
    Name = "openStoryboard",
    Duration = time
};
DoubleAnimation d = new DoubleAnimation(1, time)
{
    EasingFunction = new BackEase()
    {
        Amplitude = 0.4,
        EasingMode = EasingMode.EaseOut,
    }
};

ObjectAnimationUsingKeyFrames oaukf = new ObjectAnimationUsingKeyFrames
{
    Duration = time,
};
DiscreteObjectKeyFrame dis = new DiscreteObjectKeyFrame(Visibility.Visible, new KeyTime());

openStoryboard.Children.Add(d);
openStoryboard.Children.Add(oaukf);

cc.Resources.Add(openStoryboard.Name, openStoryboard);

Storyboard.SetTargetName(cc, "ContentControl");

我在做什么错?我有点迷路了。任何提示/建议都很好!

1 个答案:

答案 0 :(得分:2)

更正此行

Storyboard.SetTargetName(cc, "ContentControl");

使用

//Double animation
Storyboard.SetTarget(d, ContentControl); // <-- change here
Storyboard.SetTargetProperty(d, new PropertyPath("Opacity")); // <-- for WPF

还更正其他动画的TargetName和TargetProperty

要添加离散动画,请使用ObjectAnimationUsingKeyFrames的KeyFrames属性

ObjectAnimationUsingKeyFrames oaukf = new ObjectAnimationUsingKeyFrames
{
    Duration = time,
    KeyFrames = 
    {
    new DiscreteObjectKeyFrame(Visibility.Visible, new KeyTime())
    }
};