URI作为资源

时间:2014-10-08 09:43:45

标签: c# wpf

我想将SoundPlayerAction的Source属性指定为资源。我尝试了以下方法,但这不起作用,因为字符串不是需要Uri的属性的有效值。

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

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

有没有办法让它发挥作用?

2 个答案:

答案 0 :(得分:2)

将XML名称空间声明为

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

和资源

<sys:Uri x:Key="Test">/SoundFile.wav</sys:Uri>
如果声音文件是汇编资源,则

或者可能为Resource File Pack URI

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

答案 1 :(得分:1)

我发现唯一可行的解​​决方案是使用转换器:

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();
    }
}

然后在xaml文件中:

<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}" />
相关问题