1

列表中的一个属性需要很长时间才能加载(即时创建缩略图)。如何在列表中显示其余属性并在后台加载长处理属性。

以下示例显示了这种情况。我希望能够立即显示短名称和可用的长名称。

public partial class MainWindow 
{
    public MainWindow()
    {
        InitializeComponent();

        var list = new List<Example> {
            new Example {ShortName = "A", LongName = "Z"}, 
            new Example {ShortName = "B", LongName = "ZZ"}, 
            new Example {ShortName = "C", LongName = "ZZZ"}};
        DataContext = list;
    }
}

public class Example : INotifyPropertyChanged
{
    private String _shortName;
    public String ShortName
    {
        get { return _shortName; }
        set
        {
            if (_shortName == value) return;
            _shortName = value;
            NotifyPropertyChanged("ShortName");
        }
    }

    private String _longName;
    public String LongName
    {
        get
        {
            System.Threading.Thread.Sleep(1000);
            return _longName;
        }
        set
        {
            if (_longName == value) return;
            _longName = value;
            NotifyPropertyChanged("LongName");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string p)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(p));
    }
}

XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListBox ItemsSource="{Binding}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Label>ShortName: </Label>
                        <Label Content="{Binding ShortName}" />
                        <Label> LongName:</Label>
                        <Label Content="{Binding LongName}" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>

        </ListBox>
    </Grid>
</Window>
4

1 回答 1

6

您可以使用IsAsync绑定属性异步加载该属性:

<Label Content="{Binding Path=LongName,IsAsync=true}" />

您还可以使用Fallback属性来显示类似于Loading的消息,直到填充实际值。

于 2012-08-20T21:35:59.423 回答