Search code examples
c#xamlbindingwindows-phone-8longlistselector

UnhandledException when Binding Image URL in LongListSelector


            List<string> images = new List<string>();
            // add some image url to list
            DataContext = images;

I have a list of Image URL and i want to display it using LongListSelector

            <phone:LongListSelector ItemsSource="{Binding}" LayoutMode="List">
                <phone:LongListSelector.ItemTemplate>
                    <DataTemplate>
                        <Image Source="{Binding}" Stretch="UniformToFill" />
                    </DataTemplate>
                </phone:LongListSelector.ItemTemplate>
            </phone:LongListSelector>

But after xaml page display completed, debug jump to method Application_UnhandledException in App.xaml.cs, what is the problem?


Solution

  • Try this code:
    In xaml:

     <phone:LongListSelector Name="myLLS" LayoutMode="List" Height="300">
                <phone:LongListSelector.ItemTemplate>
                    <DataTemplate>
                        <Image Source="{Binding}" Height="60"/>
                    </DataTemplate>
                </phone:LongListSelector.ItemTemplate>
     </phone:LongListSelector>
    

    In code behind:

     ObservableCollection<Uri> myList = new ObservableCollection<Uri>();
    
      public MainPage()
      {
         InitializeComponent();
    
         myLLS.ItemsSource = myList;
         myList.Add(new Uri("Resources/Image1.png", UriKind.RelativeOrAbsolute));
         myList.Add(new Uri("Resources/Image2.png", UriKind.RelativeOrAbsolute));
      }
    

    I've bound LLS itemssource to ObservableCollection of Uri's. It's working. ObservableCollection is also better here, as you can dynamically update your LLS - when you add or remove image. It's also good to fix the height of LLS, without that I sometimes got an exception.