也许这是一个愚蠢的问题,因为我刚开始使用silverlight。在Silverlight和双向数据绑定中缓存图像
我有一个ListBox控件绑定到CollectionViewSource,这个CollectionViewSource被RIA服务填充。数据源中的每个项目都有一个ThumbnailPath属性,其中包含服务器上图像的字符串URL。然后在项目模板上我有一个用户控件,它有一个Image控件和一个依赖属性Source来设置Image源。源被绑定到项目的ThumbnailPath属性,并且一切正常。
但是,每次执行过滤或分页列表框时,silverlight应用程序都会向服务器请求图像。我的想法是将一个BitmapImage字段添加到该项目中,并将该图像存储在Image控件的ImageOpened事件的此字段中,然后下次使用此图像而不是ThumbnailPath。但如何实现这一点?双向绑定?我花了很多时间阅读关于双向数据绑定的知识,但仍不知道如何做到这一点。任何人都可以给我一个很好的例子或文章?
这是项目模板:
<ControlTemplate x:Key="ItemTemplate">
<Grid Width="104" Height="134" Margin="0,0,5,5" Background="White" HorizontalAlignment="Center" VerticalAlignment="Center">
<Border BorderBrush="#FF000000" BorderThickness="2, 2, 2, 2" Margin="0,0,0,0" CornerRadius="0" />
<Grid HorizontalAlignment="Center" VerticalAlignment="Center">
<my:ImageProgress Source="{Binding ThumbPath}"></my:ImageProgress>
<Grid Background="White" Margin="0,110,0,0" Opacity="0.5" Width="100" Height="20">
</Grid>
<TextBlock Text="{Binding Name}" HorizontalAlignment="Center" Margin="0,110,0,0">
</TextBlock>
</Grid>
</Grid>
</ControlTemplate>
和用户控件:
<Grid x:Name="LayoutRoot" Background="Transparent" Width="100" Height="100">
<Image x:Name="Image" Stretch="Uniform" ImageFailed="ImageFailed" ImageOpened="ImageOpened">
</Image>
<TextBlock x:Name="FailureText" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="10" TextWrapping="Wrap" Margin="20,0,20,0" Visibility="Collapsed">
image not found
</TextBlock>
</Grid>
控制代码:
public partial class ImageProgress : UserControl
{
public ImageProgress()
{
InitializeComponent();
}
public BitmapImage Source
{
get { return (BitmapImage)GetValue(SourceProperty); }
set
{
SetValue(SourceProperty, value);
Image.Source = value;
}
}
public static readonly DependencyProperty SourceProperty = DependencyProperty.Register("Source", typeof(BitmapImage), typeof(ImageProgress), new PropertyMetadata(new PropertyChangedCallback(OnSourceChanged)));
private static void OnSourceChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var source = sender as ImageProgress;
if (source != null)
{
source.Source = (BitmapImage) e.NewValue;
}
}
void ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
var img = (Image) sender;
FailureText.Visibility = Visibility.Visible;
img.Visibility = Visibility.Collapsed;
}
private void ImageOpened(object sender, RoutedEventArgs e)
{
var img = (Image)sender;
// ???
}
}