我将图像存储到网络库中。如果第一台服务器不可用,我想有一个替代路径来加载图像。
类似的东西:
<Image Source="http://server1/images/image1"
AlternativeSource="http://server2/images/image1"/>
怎么做?
答案 0 :(得分:1)
Lucky for us图像控件在加载图像失败时会引发事件,因此很容易检查图像加载是否失败。
您可以采取的一种方法是扩展图像控制。
public class AlternativeImage : Image
{
private bool _tryAlternativeSource ;
public string AlternativeSource
{
get { return (string)GetValue(AlternativeSourceProperty); }
set { SetValue(AlternativeSourceProperty, value); }
}
// Using a DependencyProperty as the backing store for ItemTemplate. This enables animation, styling, binding, etc...
public static readonly DependencyProperty AlternativeSourceProperty =
DependencyProperty.Register("AlternativeSource", typeof(string), typeof(AlternativeImage), new PropertyMetadata(null));
public AlternativeImage()
{
Initialized += OnInitialized;
}
private void OnInitialized(object sender, EventArgs eventArgs)
{
_tryAlternativeSource = !string.IsNullOrEmpty(AlternativeSource);
//Note , ths need to be unregistered
ImageFailed += OnImageFailed;
}
private void OnImageFailed(object sender, ExceptionRoutedEventArgs exceptionRoutedEventArgs)
{
if (!_tryAlternativeSource)
return;
_tryAlternativeSource = false;
Source = new ImageSourceConverter().ConvertFromString(AlternativeSource) as ImageSource;
}
}
然后像这样使用它
<controls:AlternativeImage Source="http://server1/images/image1"
AlternativeSource="https://media.licdn.com/mpr/mpr/p/1/005/07f/0e1/07ab226.jpg"/>
上传完整代码Here