如何在后面的代码中添加带有SoundActions的EventTrigger
本文关键字:SoundActions EventTrigger 添加 在后面 代码 | 更新日期: 2023-09-27 18:14:02
所以我试图在飞行中创建控件(RegularPolygon确切地说),我想添加2个PlaySoundActions到控件作为基于Tap事件的EventTrigger。目前我有以下代码:
EventTrigger trigger = new EventTrigger();
PlaySoundAction correct = new PlaySoundAction();
PlaySoundAction incorrect = new PlaySoundAction();
correct.Source = new Uri("/Sounds/Correct.mp3");
correct.Volume = 0.5;
incorrect.Source = new Uri("/Sounds/Incorrect.mp3");
incorrect.Volume = 0.5;
trigger.Actions.Add(correct); // this line doesn't work
trigger.Actions.Add(incorrect); // this also doesn't work
shape.Triggers.Add(trigger);
每一行都有一个类似
的错误错误2参数1:不能从"Microsoft.Expression.Interactivity.Media。PlaySoundAction"System.Windows.TriggerAction"
我不完全确定要将PlaySoundAction对象转换为什么。我不想在XAML中这样做,因为我正在动态地创建这些控件。
我还尝试为RegularPolygon创建一个样式,以使EventTrigger具有PlaySoundAction(s),但是以编程方式设置控件的样式并没有将此逻辑添加到控件中。
<Application.Resources>
<ResourceDictionary>
<Style TargetType="es:RegularPolygon" x:Key="Default">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Tap">
<eim:PlaySoundAction Source="/Sounds/Incorrect.mp3" Volume="0.5" />
<eim:PlaySoundAction Source="/Sounds/Correct.mp3" Volume="0.5" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Style>
</ResourceDictionary>
</Application.Resources>
是否有办法在代码后面添加EventTrigger/PlaySoundAction或创建一个控件可以继承的样式,从有一个EventTrigger/PlaySoundAction?
也许知道你在代码中使用System.Windows.EventTrigger而不是system . windows . interactive . eventtrigger会有所帮助。当我明确地指定-我让它工作:
System.Windows.Interactivity.EventTrigger trigger =
new System.Windows.Interactivity.EventTrigger();
trigger.EventName = "MouseLeftButtonDown";
PlaySoundAction correct = new PlaySoundAction();
correct.Source = new Uri("/Sample.wma", UriKind.Relative);
correct.Volume = 1.0;
trigger.Actions.Add(correct);
trigger.Attach(myTextBlock);
你需要确保你的控件也可以被点击- IsHitTestVisible不能被设置为false,它需要有一个填充画笔设置。不确定自定义控件的作用
这是我的XAML:
<Grid
x:Name="ContentPanel"
Background="LightCoral"
Tap="ContentPanel_Tap"
Grid.Row="1"
Margin="12,0,12,0" >
<StackPanel>
<TextBlock
Text="XAML Test">
<i:Interaction.Triggers>
<i:EventTrigger
EventName="MouseLeftButtonDown">
<eim:PlaySoundAction
Source="/Balloon.wav"
Volume="1" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBlock>
<TextBlock
Margin="0,100,0,0"
x:Name="myTextBlock"
Text="Coded Test" />
</StackPanel>
</Grid>