也許這是一個愚蠢的問題,因爲我剛開始使用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;
// ???
}
}