按下应用程序按钮时播放声音

时间:2012-06-01 15:50:48

标签: c# wpf xaml

我有一个应该在触摸屏上使用的WPF应用程序。对于整个应用程序,当屏幕上按下按钮时,我被要求播放声音。 我的想法是创建一个样式来执行此操作,在我的应用程序中包含资源字典。它工作得很好。 但是,这个样式是在一个单独的DLL中,我希望我的主应用程序更改声音文件的路径(下面的BoutonClickSound Url)。但我找不到办法。 我尝试了几个丑陋的事情,如:

    System.Windows.Application.Current.Resources.MergedDictionaries[0]["BoutonClickSound"] = new Uri(m_MainVM.ButClickSoundPath);
System.Windows.Application.Current.Resources.MergedDictionaries[0].MergedDictionaries[0]["BoutonClickSound"] = new Uri(m_MainVM.ButClickSoundPath);

但它们似乎都不起作用......

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:primitives="clr-namespace:System.Windows.Controls.Primitives;assembly=PresentationFramework"
                xmlns:sys="clr-namespace:System;assembly=System">

<sys:Uri x:Key="BoutonClickSound">c:\buttonclick.wav</sys:Uri>

<Style TargetType="{x:Type FrameworkElement}"  x:Key="SoundButton">
    <Style.Triggers>
        <EventTrigger RoutedEvent="PreviewMouseDown">
            <SoundPlayerAction x:Name="SoundPlayer" Source="{DynamicResource BoutonClickSound}" />
        </EventTrigger>
    </Style.Triggers>
</Style>

<Style TargetType="{x:Type primitives:Selector}"  x:Key="SoundSelectionChange">
    <Style.Triggers>
        <EventTrigger RoutedEvent="SelectionChanged">
            <SoundPlayerAction x:Name="SoundPlayer" Source="{DynamicResource BoutonClickSound}" />
        </EventTrigger>
    </Style.Triggers>
</Style>

知道怎么做吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

只需使用相同的密钥声明本地资源。

如果您想在应用程序中全局使用它,可以在中包含库中的MergedDictionary后将其添加到MergedDictionary

添加另一个条目:

<sys:Uri x:Key="BoutonClickSound">c:\differentfile.wav</sys:Uri>

它应该会使你的风格改为使用该文件。

修改

要在代码隐藏中设置资源,首先必须将其添加到本地资源字典中:

Resources.Add("BoutonClickSound", new Uri("your uri here"));

添加后,如果您想稍后更改它,则无法重新添加,您必须对其进行修改:

Resources["BoutonClickSound"] = new Uri("your uri here");