将图像绑定到ImageBrush

时间:2018-02-06 18:40:32

标签: c# xaml

我在尝试将图像绑定到ImageSource时遇到问题。我已经在stackoverflow上尝试了一些其他修复,但没有一个能够正常工作。

我似乎在这一行上收到错误,说收集" Items"必须是空的。

ImageList.ItemsSource = List;

使用" url"绑定效果很好FlickrData类的成员。

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

MainWindow类

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

1 个答案:

答案 0 :(得分:0)

这样做是为了清理过程

  1. 将您的XAML ListView更改为ItemsSource="{Binding List}",只需执行一次。
  2. 删除现在多余的ImageList.ItemsSource = List;
  3. 列表控件将相应地更新自身,因为ObservableCollection会发送列表控件订阅的更改通知。