如何在代码中添加带有SoundActions的EventTrigger?

时间:2011-11-11 01:49:11

标签: c# silverlight windows-phone-7

所以我正在尝试动态创建控件(准确地说是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创建一个Style,使EventTrigger具有PlaySoundAction,但是以编程方式设置控件的样式不会将此逻辑添加到控件中。

<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?

1 个答案:

答案 0 :(得分:5)

也许知道您尝试在代码中使用System.Windows.EventTrigger而不是System.Windows.Interactivity.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>