【发布时间】:2011-06-22 09:22:34
【问题描述】:
也许这是一个愚蠢的问题,因为我刚刚开始使用 silverlight。
我有一个绑定到 CollectionViewSource 的 ListBox 控件,并且此 CollectionViewSource 由 RIA 服务填充。数据源中的每个项目都有一个 ThumbnailPath 属性,其中包含服务器上图像的字符串 URL。然后在项目模板上我有一个用户控件,它有一个 Image 控件和一个依赖属性 Source 来设置 Image 源。 Source 绑定到项目的 ThumbnailPath 属性,一切正常。
但是,silverlight 应用程序在每次对 ListBox 执行过滤或分页时都会向服务器请求图像。我的想法是在项目中添加一个 BitmapImage 字段并将图像存储在 Image 控件的 ImageOpened 事件上的此字段中,然后下次使用此图像而不是 ThumbnailPath。但是如何实现呢?双向绑定?我花了很多时间阅读有关 2-way 数据绑定的信息,但仍然不知道如何做到这一点。谁能指点我一个很好的例子或文章?
这是项目模板:
<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;
// ???
}
}
【问题讨论】:
标签: .net silverlight