【问题标题】:How to reference base URLs for images in XAML in Silverlight?如何在 Silverlight 中引用 XAML 中图像的基本 URL?
【发布时间】:2010-08-18 08:27:21
【问题描述】:

我的 silverlight 应用程序中散布着图像,由于我们决定的结构,所有图像都是从 HTTP URL 引入的。

目前,在 XAML 中,图像将声明如下:

<Image Source="http://www.example.com/directory/example.png" />

我希望将引用的所有图像的基本 URL 存储在全局字符串常量中,可从所有 XAML 文件和代码隐藏文件访问。

即常量字符串 BASE_URI = "http://www.example.com/directory";

我怎样才能做到这一点并在 XAML 中引用它,同时将字符串附加到实际的图像名称?我想过使用转换器,但这需要数据绑定——这里我只是直接使用字符串。

【问题讨论】:

    标签: silverlight xaml global-variables


    【解决方案1】:

    如果没有一些重要的代码,就无法实现您想要的。正如您已经想到的,最简单的解决方案是使用转换器。确实,这需要数据绑定,因此它不像源属性上的静态值那样干净。然而,由于源属性上的静态值已经是一个问题,因此几乎没有理由避免这种方法。这是我的首选解决方案:-

    转换器:-

    public class BaseUriConverter : IValueConverter
    {
        private Uri myBaseUri;
    
        public BaseUriConverter()
        {
            myBaseUri = new Uri(Application.Current.Host.Source.AbsoluteUri); 
        }
        public string AdjustPath { get; set; }
    
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Uri uri = new Uri(myBaseUri, AdjustPath);
            Uri result = new Uri(uri, (string)parameter);
            return result.ToString();
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException("This converter only works for one way binding");
        }
    }
    

    在 App.Xaml 的资源中:-

    <local:BaseUriConverter x:Key="BaseUri" AdjustPath=".." />
    

    请注意,“..”的使用允许典型用法。 Xap 位于应用程序文件夹的 Clientbin 文件夹中。因此,图像可以存储在相对于应用程序文件夹的公共文件夹中,无论该站点是在 Visual Studio 中运行还是作为根站点安装在 IIS 中,这都有效。

    然后页面中某处的图像可能如下所示:-

    <Image DataContext="0" Source="{Binding Converter={StaticResource BaseUri}, ConverterParameter='images/Test.jpg' }"  />
    

    请注意 DataContext 属性已设置,因此会发生绑定,转换器不会打扰值是什么。在这种情况下,路径也是相对的。

    在您的具体示例中,您可以在代码中将您的固定 baseURL 分配给转换器的 AdjustPath 属性,但是我怀疑目前这将满足您的需求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多