简体   繁体   中英

Binding an image to ImageBrush

i am having an issue while trying to bind an image to an ImageSource. I have tried some of the other fix on stackoverflow but none of them works.

I seem to get an error on this line saying that collection "Items" must be empty.

ImageList.ItemsSource = List;

The bind works well while using the "url" member of the FlickrData class.

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 Class :

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;
          }
      }
}

MainWindow class :

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;
    }
}

Do this to clean up the process

  1. Change your XAML's ListView to ItemsSource="{Binding List}" which only needs to be done once.
  2. Remove the now redundant ImageList.ItemsSource = List;

The list control will update itself accordingly because an ObservableCollection sends notifications of the change which are subscribed to by the list control.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM