【问题标题】:WPF ListBox Aynchronous BindingWPF ListBox 异步绑定
【发布时间】:2011-08-22 19:53:52
【问题描述】:

我有一个列表框,它执行动态填充的自动完成功能。列表框显示带有员工照片的姓名列表。我发现用图像填充数据很慢。

我希望能够先填充名称,然后在收到数据时异步上传数据。我该怎么做?

目前我的Image类代码:

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

填充数据的代码:

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

我的 XAML 代码:

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

目前,它同时填充所有名称+图像...这导致列表框慢得令人难以忍受。

提前致谢

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    好的,您缺少两件东西才能使图像延迟加载正常工作....

    1. PriorityBinding 按缓慢加载然后快速加载图像源的顺序。
    2. DownloadCompleted 每个图像的事件必须通知绑定的更改,它已准备好显示。

    看看这两个帖子,看看能不能得到提示……

    How to lazy load image byte[] into a WPF image control?

    initial image in WPF Image Control

    如果这有帮助,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-02
      • 1970-01-01
      • 1970-01-01
      • 2014-06-11
      • 2017-03-30
      • 2016-10-11
      相关资源
      最近更新 更多