为什么在AsyncTaskManager中PropertyChanged始终为null? [英] Why in AsyncTaskManager PropertyChanged is always null?

查看:59
本文介绍了为什么在AsyncTaskManager中PropertyChanged始终为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试实现与本文介绍的模式类似的东西: http://msdn.microsoft.com/en-us/magazine/dn605875.aspx

I Try to implement sth similar to the pattern presented in this article: 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}"

然后在代码背后:

this.DataContext = new ProductViewModel();

然后在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());      
    }

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

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

但是当我删除加载数据"按钮和_loadDataCommand时,只需设置

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

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

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

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

下面是AsyncTaskManager代码:

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

}

推荐答案

请尝试创建最少的可复制代码集,并在调试器中观察输出"窗口中的数据绑定错误.

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

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

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.

这篇关于为什么在AsyncTaskManager中PropertyChanged始终为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆