После долгих проб и ошибок я нашел обходной путь, который, как я думал, я бы поделился.
Я создал новый класс ImageData
для инкапсуляции относительного Uri, который мне нужно было загрузить в элемент управления Image
.
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);
}
Наконец, я создал DataTemplate
в XAML, снова для удобства в файле 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
, а затем при повторной загрузке XAML с использованием XamlReader.Load
DataTemplate связывается со свойством ImageSource
, которое преобразует относительный путь в абсолютный один как можно позже.