【问题标题】:Convert pack:// URI to relative URI将 pack:// URI 转换为相对 URI
【发布时间】:2012-02-04 08:03:26
【问题描述】:

在使用XamlWriter 进行序列化期间,我正在尝试序列化Image 控件。这些控件的这些Source 属性设置为相对URI。

但是,在使用XamlWriter 进行序列化后,Image 控件包含如下路径:

原始路径

../test.png

XamlWriter 路径

pack://application:,,,/test.png

有什么方法可以防止XamlWriter 将相对路径更改为打包路径?

【问题讨论】:

标签: c# wpf xaml serialization


【解决方案1】:

经过大量试验和错误后,我想出了一个解决方法,我认为我会分享。

我创建了新类ImageData 来封装我需要加载到Image 控件中的相关Uri。

public class ImageData
{
    /// <summary>
    /// Relative path to image
    /// </summary>
    public string ImageSourceUri { get; set; }

    public ImageSource ImageSource
    {
        get { return new BitmapImage(App.GetPathUri(ImageSourceUri)); }
    }
}

然后我在App 类中创建了一个函数(为了方便)将相对路径转换为绝对Uri。

    /// <summary>
    /// Converts a relative path from the current directory to an absolute path 
    /// </summary>
    /// <param name="relativePath">Relative path from the current directory</param>
    public static string GetPath(string relativePath)
    {
        return System.IO.Path.Combine(Environment.CurrentDirectory, relativePath);
    }

    /// <summary>
    /// Converts a relative path from the current directory to an absolute Uri 
    /// </summary>
    /// <param name="relativePath">Relative path from the current directory</param>
    public static Uri GetPathUri(string relativePath)
    {
        return new Uri(GetPath(relativePath), UriKind.Absolute);
    }

最后,为了方便,我在 XAML 中创建了一个 DataTemplate,再次在 App.xaml 文件中:

<Application.Resources>
    <DataTemplate DataType="{x:Type local:ImageData}">
        <Image Source="{Binding Path=ImageSource}"></Image>
    </DataTemplate>
</Application.Resources>

现在调用XamlWriter.Save 方法时,输出的XAML 如下所示:

<d:ImageData ImageSourceUri="test_local.png" />

因此路径被存储为string 类型的相对路径,然后当使用XamlReader.Load 再次加载XAML 时,DataTemplate 绑定到ImageSource 属性,该属性将相对路径转换为绝对路径越晚越好。

【讨论】:

  • 附带说明,是否将 GetPath 逻辑放置在 App 类中是设计考虑因素 - 根据上下文,将其作为私有方法放置在 ImageData 类中可能会减少耦合。 .
猜你喜欢
  • 1970-01-01
  • 2014-07-15
  • 2011-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-13
  • 2014-03-26
相关资源
最近更新 更多