在使用XamlWriter
序列化期間,除其他外我試圖序列化Image
控件。這些控件的這些Source
屬性設置爲相對URI。轉換包:// URI到相對URI
然而,隨着XamlWriter
序列化之後,Image
控件包含路徑是這樣的:
原始路徑
../test.png
的XamlWriter路徑
pack://application:,,,/test.png
有什麼辦法以防止ch。的XamlWriter
老化相對路徑來打包路徑?
在使用XamlWriter
序列化期間,除其他外我試圖序列化Image
控件。這些控件的這些Source
屬性設置爲相對URI。轉換包:// URI到相對URI
然而,隨着XamlWriter
序列化之後,Image
控件包含路徑是這樣的:
原始路徑
../test.png
的XamlWriter路徑
pack://application:,,,/test.png
有什麼辦法以防止ch。的XamlWriter
老化相對路徑來打包路徑?
經過大量的試驗和錯誤,我想出了一個我認爲我會分享的解決方法。
我創建了新類,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);
}
最後,我在App.xaml文件中創建XAML中DataTemplate
,再次爲方便:
<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再次使用01被裝載,DataTemplate綁定到ImageSource
屬性,該屬性儘可能晚地將相對路徑轉換爲絕對路徑。
作爲一個方面說明,是否放置GetPath App類中的邏輯或不是設計的考慮因素 - 根據上下文的不同,它可能會減少耦合,將其作爲ImageData類中的私有方法。 – ose 2012-02-04 11:40:24
看看這個問題:http://stackoverflow.com/questions/6495253/how-to-prevent-xamlwriter-save-from-serializing-the-baseuri-property – Corylulu 2012-02-04 09:40:52