我在ResourceDirectory中定义了一个样式代码来为弹出窗口设置动画。这是WPF代码:
<Style x:Key="Hardwarepopups" TargetType="Popup">
<Style.Triggers>
<Trigger Property="IsOpen" Value="True">
<Trigger.EnterActions>
<BeginStoryboard >
<Storyboard>
<DoubleAnimation Duration="0:0:.3" Storyboard.TargetProperty="Width" From="0" To="100" AccelerationRatio=".1"/>
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
</Trigger>
</Style.Triggers>
</Style>
这是弹出窗口:
<Popup Height="Auto" Width="Auto" Name="HardwareToolTip" StaysOpen="True" AllowsTransparency="True" Style="{StaticResource Hardwarepopups}">
通过处理XAML中的所有内容,效果很好。我决定将其转换为C#代码,如下所示:
void SetHarwareStyle(Popup B) {
var RightToLeft = new DoubleAnimation()
{
From = 0,
To = 100,
Duration = TimeSpan.FromMilliseconds(300),
AccelerationRatio = 0.1
};
Storyboard.SetTargetProperty(RightToLeft, new PropertyPath(WidthProperty));
Storyboard C = new Storyboard();
C.Children.Add(RightToLeft);
var action = new BeginStoryboard();
action.Storyboard = C;
Trigger A = new Trigger { Property = Popup.IsOpenProperty, Value = true };
A.EnterActions.Add(action);
B.Triggers.Add(A);
}
但是这一行B.Triggers.Add(A);
给出了错误System.InvalidOperationException: 'Triggers collection members must be of type EventTrigger.'
我怎么解决这个问题?
这种转换的建议是在运行时更改To
的{{1}}属性。
答案 0 :(得分:1)
问题中的代码不能完全反映XAML:缺少样式。
我重命名了一些变量以使其更易于阅读(并防止出现此类错误)
顺便说一句:rightToLeftAnimation应该命名为leftToRightAnimation。
void SetHarwareStyle(Popup popup)
{
var rightToLeftAnimation = new DoubleAnimation()
{
From = 0,
To = 100,
Duration = TimeSpan.FromMilliseconds(300),
AccelerationRatio = 0.1
};
Storyboard.SetTargetProperty(rightToLeftAnimation, new PropertyPath(WidthProperty));
var storyboard = new Storyboard();
storyboard.Children.Add(rightToLeftAnimation);
var beginStoryboard = new BeginStoryboard();
beginStoryboard.Storyboard = storyboard;
var trigger = new Trigger { Property = Popup.IsOpenProperty, Value = true };
trigger.EnterActions.Add(beginStoryboard);
var style= new Style();
style.TargetType = typeof(Popup);
style.Triggers.Add(trigger);
popup.Style = style;
}