我在尝试将图像绑定(bind)到 ImageSource 时遇到问题。我已经尝试了一些关于 stackoverflow 的其他修复,但没有一个有效。
我似乎在这一行中收到一条错误消息,指出集合“Items”必须为空。
ImageList.ItemsSource = List;
绑定(bind)在使用 FlickrData 类的“url”成员时运行良好。
MainWindow.xaml
<ScrollViewer>
<ListView x:Name="ImageList" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<Rectangle Margin="5" Width="100" Height="100">
<Rectangle.Fill>
<ImageBrush ImageSource="{Binding imageBinding}"/>
</Rectangle.Fill>
</Rectangle>
</ListView>
</ScrollViewer>
FlickrData 类:
public class FlickrData
{
public String url { get; set;}
public FlickrData(Photo photo)
{
url = photo.SmallUrl;
}
public ImageBrush imageBinding
{
get
{
ImageBrush brush = new ImageBrush();
brush.ImageSource = new BitmapImage(new Uri(url));
return brush;
}
}
}
主窗口类:
public partial class MainWindow : Window
{
public ObservableCollection<FlickrData> List = new ObservableCollection<FlickrData>();
public static Flickr flickr = new Flickr("XXXXXXXXXXXXXX");
public MainWindow()
{
InitializeComponent();
}
public void SearchWithInput(object sender, RoutedEventArgs e)
{
var options = new PhotoSearchOptions { Tags = SearchInput.Text, PerPage = 20, Page = 1 };
PhotoCollection photos = flickr.PhotosSearch(options);
List.Clear();
foreach (Photo photo in photos)
{
String flickrUrl = photo.WebUrl;
Console.WriteLine("Photo {0} has title {1} with url {2}", photo.PhotoId, photo.Title, photo.WebUrl);
List.Add(new FlickrData(photo));
}
ImageList.ItemsSource = List;
}
}
最佳答案
这样做是为了清理进程
- 将 XAML 的
ListView
更改为ItemsSource="{Binding List}"
,只需执行一次。 - 删除现在多余的
ImageList.ItemsSource = List;
列表控件将相应地更新自身,因为 ObservableCollection
发送列表控件订阅的更改通知。
关于c# - 将图像绑定(bind)到 ImageBrush,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48649773/