为什么在AsyncTaskManager中PropertyChanged总是为空?

时间:2014-04-15 17:18:47

标签: c# .net mvvm async-await

我尝试实现类似于本文中提供的模式: http://msdn.microsoft.com/en-us/magazine/dn605875.aspx

以下是我的问题描述:

在我的视图中,我设置了:

<Button Content="LoadData" Command="{Binding LoadDataCommand}" />
<ListBox Grid.Row="1" x:Name="listBox" ItemsSource="{Binding DataSource.Result}"

然后在codeBehind:

this.DataContext = new ProductViewModel();

然后在ProductViewModel中:

public AsyncTaskManager<ObservableCollection<Product>> DataSource { get; private set; }

public ProductViewModel()
    {
        _loadDataCommand = new DelegateCommand(LoadDataAction);

    }
private void LoadDataAction(object p)
    {
        ProductRepository pRepository = new ProductRepository();
        DataSource = new AsyncTaskManager<ObservableCollection<Product>>(pRepository.LoadProducts());      
    }

在AsyncTaskManager中,PropertyChanged始终为null :(为什么会这样?绑定有什么问题?

但是当我删除&#34;加载数据&#34;按钮和_loadDataCommand,只需设置

即可
ProductRepository pRepository = new ProductRepository();
        DataSource = new AsyncTaskManager<ObservableCollection<Product>>(pRepository.LoadProducts());   
ProductViewModel构造函数中的

然后它就像在示例中一样工作,但是我希望用户可以使用按钮而不是在构造函数的start中调用加载数据:/

下面是AsyncTaskManager代码:

using System;
using System.ComponentModel;
using System.Threading.Tasks;

namespace PhoneClientApp.Models
{
    public sealed class AsyncTaskManager<TResult> : INotifyPropertyChanged
    {
    public AsyncTaskManager(Task<TResult> task)
    {
        Task = task;
        if (!task.IsCompleted)
        {
            var _ = WatchTaskAsync(task);
        }
    }

    private async Task WatchTaskAsync(Task task)
    {
        try
        {
            await task;
        }
        catch
        {
        }
        var propertyChanged = PropertyChanged;
        if (propertyChanged == null)
            return;
        propertyChanged(this, new PropertyChangedEventArgs("Status"));
        propertyChanged(this, new PropertyChangedEventArgs("IsCompleted"));
        propertyChanged(this, new PropertyChangedEventArgs("IsNotCompleted"));
        if (task.IsCanceled)
        {
            propertyChanged(this, new PropertyChangedEventArgs("IsCanceled"));
        }
        else if (task.IsFaulted)
        {
            propertyChanged(this, new PropertyChangedEventArgs("IsFaulted"));
            propertyChanged(this, new PropertyChangedEventArgs("Exception"));
            propertyChanged(this,
                new PropertyChangedEventArgs("InnerException"));
            propertyChanged(this, new PropertyChangedEventArgs("ErrorMessage"));
        }
        else
        {
            propertyChanged(this,
                new PropertyChangedEventArgs("IsSuccessfullyCompleted"));
            propertyChanged(this, new PropertyChangedEventArgs("Result"));
        }
    }

    public Task<TResult> Task { get; private set; }

    public TResult Result
    {
        get
        {
            return (Task.Status == TaskStatus.RanToCompletion)
                ? Task.Result
                : default(TResult);
        }
    }

    public TaskStatus Status
    {
        get { return Task.Status; }
    }

    public bool IsCompleted
    {
        get { return Task.IsCompleted; }
    }

    public bool IsNotCompleted
    {
        get { return !Task.IsCompleted; }
    }

    public bool IsSuccessfullyCompleted
    {
        get
        {
            return Task.Status ==
                   TaskStatus.RanToCompletion;
        }
    }

    public bool IsCanceled
    {
        get { return Task.IsCanceled; }
    }

    public bool IsFaulted
    {
        get { return Task.IsFaulted; }
    }

    public AggregateException Exception
    {
        get { return Task.Exception; }
    }

    public Exception InnerException
    {
        get
        {
            return (Exception == null)
                ? null
                : Exception.InnerException;
        }
    }

    public string ErrorMessage
    {
        get
        {
            return (InnerException == null)
                ? null
                : InnerException.Message;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

}

1 个答案:

答案 0 :(得分:2)

请尝试创建一组可重复的最小代码,并在调试器中观察输出窗口是否存在数据绑定错误。

以下代码对我来说很合适(在LINQPad中):

void Main()
{
    var context = new ParserContext();
    context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
    var xaml = @"<Grid><ListBox ItemsSource=""{Binding DataSource.Result}"" /></Grid>";
    var element = (FrameworkElement)XamlReader.Parse(xaml, context);
    element.DataContext = new ProductViewModel();

    PanelManager.StackWpfElement(element);
}

class ProductViewModel
{
    public ProductViewModel()
    {
        DataSource = new AsyncTaskManager<ObservableCollection<string>>(LoadProductsAsync());
    }

    private async Task<ObservableCollection<string>> LoadProductsAsync()
    {
        await Task.Delay(10000);
        return new ObservableCollection<string> { "first", "second", "third" };
    }

    public AsyncTaskManager<ObservableCollection<string>> DataSource { get; private set; }
}

列表框首先显示为空,然后在延迟后填充值。