I have a list box that performs auto-complete feature which populates dynamically. The listbox displays a list of names with the employee's picture. I find that populating data with image slow.
I would like to be able to populate the names first and then upload the data asynchronously as and when it is received. How do I go about doing so?
My Image class code at the moment:
public class Img : INotifyPropertyChanged
{
private string name;
private Image image;
public event PropertyChangedEventHandler PropertyChanged;
public Img(string name, Image image)
{
this.name = name;
this.image = image;
}
public string Name
{
get { return name; }
set
{
name = value;
OnPropertyChanged("PersonName");
}
}
public Image Image
{
get { return image; }
set
{
image = value;
OnPropertyChanged("Image");
}
}
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
The code that populates the data:
foreach (KeyValuePair<string, string> entry in items)
{
System.Windows.Controls.Image webImage = new System.Windows.Controls.Image();
webImage.Dispatcher.Invoke(DispatcherPriority.Normal,
(ThreadStart)delegate
{
BitmapImage image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(//Where the source is);
image.EndInit();
webImage.Source = image;
});
myListBox.Items.Add(new Img(entry.Value, webImage));
}
My XAML code:
<Popup Name="myPopUp">
<ListBox Name="myListBox" FontSize="14">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type local:Img}">
<StackPanel Orientation="Horizontal">
<ContentPresenter Margin="3" Content="{Binding Image, IsAsync=True}"/>
<TextBlock Margin="3" Text="{Binding Name, IsAsync=True}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Popup>
At the moment, it populates all the names + images at the same time...which causes the listbox to be unbearably slow.
Thanks in advance