2012-06-01 42 views
0

我有一個應該在觸摸屏上使用的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> 

任何想法如何做到這一點?

謝謝。

回答

0

只需使用相同的密鑰聲明本地資源。

如果您希望在您的應用程序中使用它,可以將其添加到合併詞典之後包含庫中的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"); 
+0

moozhe,謝謝你的回覆。如果我想通過後面的代碼設置BoutonClickSound URI呢? – LPL

+0

編輯我的答案。 –

+0

是否有可能在App.xaml(和.cs)中執行它?我在App.xaml中添加了ResourceDictionary,之後添加了本地鍵。這工作正常。但是當我嘗試用'Resources [「BoutonClickSound」] = new Uri(filepath);'來更改App.cs應用程序啓動事件時,它似乎沒有更新聲音文件...實際上wav文件的名稱播放將來自配置文件,因此在編譯時不會知道。 – LPL