经过大量试验和错误后,我想出了一个解决方法,我认为我会分享。
我创建了新类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 属性,该属性将相对路径转换为绝对路径越晚越好。