Frage

I'm creating a windows 8 metro styled app for the windows store.

I've got a resource dictionary (which has "code behind") which is merged in app.xaml as

<Application.Resources>
    <ResourceDictionary>     
        <ResourceDictionary.MergedDictionaries>
            <view:TemplatesDictionary />   
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

I'm using the dictionary to access templates/color brushes and swap them out during runtime based on properties/states changing.

return App.Current.Resources["SomeKey"] as Windows.UI.Xaml.Media.SolidColorBrush;

or whichever type I need.

This has been working fine with pretty much anything so far, however I've run into issues when trying to do the same thing with MediaElements.

I've got

<MediaElement x:Key="SFX_ButtonSound" AutoPlay="False" Source="ms-appx:///Assets/Sound/UI Click Random.wav" Volume="1" />

then in code I've tried

(App.Current.Resources["SFX_ButtonSound"] as MediaElement).Play();

and nothing plays but it can access and find the key fine.

However, if I copy paste the media element into a page, changed x:key to x:name then

SFX_ButtonSound.Play();

It will play fine, can someone explain to me why this occurs? I'm assuming it doesn't function because an instance of the media element on the page hasn't been "created" or something like that.

I've not done much WPF/Silver-light development/UI dev. I mainly focus in just backend dev.

Edit: So in case anyone was wondering, the reason why I attempted to approach it this way was so that i could, in code, manage whether or not volume was muted via in-app control as well as other various things and so that everything could be in one centralized "place" and so in code, when needed, i could simply call something like

Media.PlaySFX(string)

and it would apply the current settings/variables I needed at the time. What i ended up doing to achieve this was create a User control which simply contained all my generic media elements (button clicks, ambient sounds, etc).

Then in each of my pages which required the sounds, I just created the control in the .resources area.

For the C# file for the user control it has a few functions to just play/stop/test logic.

War es hilfreich?

Lösung

I believe a MediaElement needs to be a part of visual tree to work, so indeed you need to add it somewhere. Maybe a Popup would work?

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top