raeffs
raeffs

Reputation: 605

URI as resource

I would like to specify the Source property of a SoundPlayerAction as resource. I tried the following, but this does not work because a string is not a valid value for the property which expects a Uri.

<Window.Resources>
<sys:String x:Key="Test">/SoundFile.wav</sys:String>
</Window.Resources>

<SoundPlayerAction Source="{DynamicResorce Test}" />

Is there a way to bring that to work?

Upvotes: 2

Views: 860

Answers (2)

Clemens
Clemens

Reputation: 128042

Declare the XML namesspace as

xmlns:sys="clr-namespace:System;assembly=system"

and the resources as

<sys:Uri x:Key="Test">/SoundFile.wav</sys:Uri>

or perhaps as a Resource File Pack URI if the sound file is an assembly resource:

<sys:Uri x:Key="Test">pack://application:,,,/SoundFile.wav</sys:Uri>

Upvotes: 4

raeffs
raeffs

Reputation: 605

The only working solution I found was to use a converter:

public class UriConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (!(value is string)) return value;

        var filename = value as string;
        return new Uri(filename, UriKind.RelativeOrAbsolute);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

Then in the xaml file:

<Window.Resources>
    <sys:String x:Key="MyFile">/SoundFile.wav</sys:String>
    <converter:UriConverter x:Key="UriConverter" />
</Window.Resources>

<SoundPlayerAction Source="{Binding Source={StaticResource MyFile}, Converter={StaticResource UriConverter}, Mode=OneWay}" />

Upvotes: 1

Related Questions