【发布时间】:2018-08-02 03:37:53
【问题描述】:
所以我在将 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");
我做错了什么?我有点迷失在这里。任何提示/建议都会很棒!
【问题讨论】:
-
有什么特别的原因吗?
-
我想将此内容控件添加到按钮中,如果它全部在代码中而不是拥有一个 XAML 文件,这样做会更容易。也主要用于组织目的。
标签: c# wpf xaml code-behind