2012-02-04 82 views
0

在使用XamlWriter序列化期间,除其他外我试图序列化Image控件。这些控件的这些Source属性设置为相对URI。转换包:// URI到相对URI

然而,随着XamlWriter序列化之后,Image控件包含路径是这样的:

原始路径

../test.png 

的XamlWriter路径

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

有什么办法以防止ch。的XamlWriter老化相对路径来打包路径?

+0

看看这个问题:http://stackoverflow.com/questions/6495253/how-to-prevent-xamlwriter-save-from-serializing-the-baseuri-property – Corylulu 2012-02-04 09:40:52

回答

0

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

我创建了新类,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属性,该属性尽可能晚地将相对路径转换为绝对路径。

+0

作为一个方面说明,是否放置GetPath App类中的逻辑或不是设计的考虑因素 - 根据上下文的不同,它可能会减少耦合,将其作为ImageData类中的私有方法。 – ose 2012-02-04 11:40:24