WPF: Changing MediaElement source with ResourceDictionary
I want to use background music in my WPF Application. Like you can see here: How to do background music for my WPF-Application开发者_如何学编程?
So I use a MediaElement.
Now I want to change the source of it while running the Application.
I'm already doing something similar with some background pictures. There I have different ResourceDictionaries that I'm switching to show different "themes".
One of my dictionaries looks like this:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ImageBrush x:Key="Backgroundpic" ImageSource="picture.png"/>
...
</ResourceDictionary>
So I can use it in the xaml like this:
...
<Grid x:Name="Bg" Background="{DynamicResource Backgroundpic}"/>
...
But HOW can I do that with my MediaElement-Source that I can use it like this:
<MediaElement x:Name="myMediaElement" Source="{DynamicResource ???}" />
I just don't know what to write into my ResourceDictionary.
Source is a Uri, so you need your resource to be a Uri. (Note that System.Uri is in the System assembly, not mscorlib, so it needs a different XML namespace than you would use for types like String):
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=System">
<sys:Uri x:Key="mediaSource">something.mp3</sys:Uri>
Then you can reference it with Source={DynamicResource mediaSource}
.
精彩评论