这是一个简单的问题,令我惊讶的是,我找不到答案:如何在XAML中播放系统声音?
我有一个事件触发器附加到按钮.触发器显示一条消息,我希望它播放Windows Notify声音.我已经找到了几个关于如何播放声音文件的参考,但没有关于如何调用系统声音的内容.
谢谢你的帮助!
本SystemSounds类提供了一些系统声音,他们有一个Play()方法.要在XAML中使用它,您可能不得不求助于一些糟糕的黑客攻击,实现大量自定义逻辑或使用Blend Interactivity来定义您自己的TriggerAction,它可以使用SystemSound并播放它.
交互方法:
public class SystemSoundPlayerAction : System.Windows.Interactivity.TriggerAction<Button>
{
public static readonly DependencyProperty SystemSoundProperty =
DependencyProperty.Register("SystemSound", typeof(SystemSound), typeof(SystemSoundPlayerAction), new UIPropertyMetadata(null));
public SystemSound SystemSound
{
get { return (SystemSound)GetValue(SystemSoundProperty); }
set { SetValue(SystemSoundProperty, value); }
}
protected override void Invoke(object parameter)
{
if (SystemSound == null) throw new Exception("No system sound was specified");
SystemSound.Play();
}
}
Run Code Online (Sandbox Code Playgroud)
<Window
xmlns:sysmedia="clr-namespace:System.Media;assembly=System"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity">
...
<Button Content="Test2">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:EventTrigger.Actions>
<local:SystemSoundPlayerAction SystemSound="{x:Static sysmedia:SystemSounds.Beep}"/>
</i:EventTrigger.Actions>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
Run Code Online (Sandbox Code Playgroud)
(我不知道SystemSounds.Beep你是否正在寻找的那个.)
David Veeneman的注意事项:
对于研究此问题的其他人,答案中提到的Blend Interactivity需要引用System.Windows.Interactivity.dll,它位于C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\.NETFramework\v4.0\Libraries\
| 归档时间: |
|
| 查看次数: |
4261 次 |
| 最近记录: |