如果没有一些重要的代码,就无法实现您想要的。正如您已经想到的,最简单的解决方案是使用转换器。确实,这需要数据绑定,因此它不像源属性上的静态值那样干净。然而,由于源属性上的静态值已经是一个问题,因此几乎没有理由避免这种方法。这是我的首选解决方案:-
转换器:-
public class BaseUriConverter : IValueConverter
{
private Uri myBaseUri;
public BaseUriConverter()
{
myBaseUri = new Uri(Application.Current.Host.Source.AbsoluteUri);
}
public string AdjustPath { get; set; }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Uri uri = new Uri(myBaseUri, AdjustPath);
Uri result = new Uri(uri, (string)parameter);
return result.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException("This converter only works for one way binding");
}
}
在 App.Xaml 的资源中:-
<local:BaseUriConverter x:Key="BaseUri" AdjustPath=".." />
请注意,“..”的使用允许典型用法。 Xap 位于应用程序文件夹的 Clientbin 文件夹中。因此,图像可以存储在相对于应用程序文件夹的公共文件夹中,无论该站点是在 Visual Studio 中运行还是作为根站点安装在 IIS 中,这都有效。
然后页面中某处的图像可能如下所示:-
<Image DataContext="0" Source="{Binding Converter={StaticResource BaseUri}, ConverterParameter='images/Test.jpg' }" />
请注意 DataContext 属性已设置,因此会发生绑定,转换器不会打扰值是什么。在这种情况下,路径也是相对的。
在您的具体示例中,您可以在代码中将您的固定 baseURL 分配给转换器的 AdjustPath 属性,但是我怀疑目前这将满足您的需求。