Why in AsyncTaskManager PropertyChanged is always

2019-09-01 01:14发布

I Try to implement sth similar to the pattern presented in this article: http://msdn.microsoft.com/en-us/magazine/dn605875.aspx

Below is my problem description:

In my View I have set:

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

Then in codeBehind:

this.DataContext = new ProductViewModel();

Then in ProductViewModel:

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

AND:

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

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

And In AsyncTaskManager PropertyChanged is always null :( Why is that? What is wrong with the binding ?

But when I delete "load data" button and _loadDataCommand and just simply set

ProductRepository pRepository = new ProductRepository();
        DataSource = new AsyncTaskManager<ObservableCollection<Product>>(pRepository.LoadProducts());   

in the ProductViewModel constructor then it work like in the example, but I want user to have possibility to invoke load data using button not on start in constructor :/

Below is the AsyncTaskManager code:

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条回答
放我归山
2楼-- · 2019-09-01 01:42

Please try to create a minimal reproducible set of code, and observe your Output window in the debugger for data binding errors.

The following code works just fine for me (in 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; }
}

The list box is first shown empty, and then after a delay is populated with values.

查看更多
登录 后发表回答