[英]Caching images in silverlight and 2-way databinding
也許這是一個愚蠢的問題,因為我剛開始使用Silverlight。
我有一個ListBox控件,該控件綁定到CollectionViewSource,此CollectionViewSource由RIA服務填充。 數據源中的每個項目都有一個ThumbnailPath屬性,其中包含服務器上圖像的字符串URL。 然后在項目模板上,我有一個用戶控件,該控件具有一個Image控件和一個用於設置Image source的依賴項屬性Source。 源綁定到項目的ThumbnailPath屬性,並且一切正常。
但是,每次執行ListBox的篩選或分頁時,silverlight應用程序都會從服務器請求圖像。 我的想法是向該項目添加一個BitmapImage字段,並將圖像存儲在Image控件的ImageOpened事件上的該字段中,然后下次使用此圖像代替ThumbnailPath。 但是如何實現呢? 雙向綁定? 我花了很多時間閱讀有關2向數據綁定的信息,但仍然不知道該怎么做。 誰能給我指出一個好的例子或文章?
這是項目模板:
<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;
// ???
}
}
Silverlight應用程序每次都請求圖像的事實並不是真正的問題。 您應該只在Web服務器中配置緩存設置(我想您正在使用IIS),以避免整個圖像流來回傳輸。
這種方式不需要額外的代碼。 (y)
問候,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.