1

在 Windows 商店应用程序上工作,我尝试在更新某些数据时更新/刷新 listView。但是,尽管我阅读了所有样本和文档,但它不起作用......

这里是我的代码:(我不提供我的 xaml 文件,它只是一个示例 listView)。

所以实现 INotifyPropertyChanged 接口的类:

public class Download : INotifyPropertyChanged
    {
        public enum DownloadState
        {
            Running,
            Waiting,
            Pausing,
            Paused,
            Cancelling,
            Cancelled
        };

        private String Uri;
        private StorageFile storageFile;
        private String tempFileName;



        private String fileName;
        private String version ;

        private long totalSize ;
        private long downloadedBytes;

        private DownloadState state;
        private Protocol protocol;


        public Download(String Uri, StorageFile file, String fileName, String version, long totalSize, Protocol protocol)
        {
            this.Uri = Uri;
            this.storageFile = file;
            this.tempFileName = "";
            this.fileName = fileName;
            this.version = version;

            this.totalSize = totalSize;
            this.downloadedBytes = 0;

            this.state = DownloadState.Waiting;

            this.protocol = protocol;


        }


        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            System.Diagnostics.Debug.WriteLine("Update!"); //ok
            if (PropertyChanged != null)
            {
                //PropertyChanged is always null and shouldn't.
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
           public DownloadState State
        {
            get{return this.state;}
            set { 
                this.state = value;
                NotifyPropertyChanged();
            }
        }

        //+some others methods

    }
}

Metro应用程序的主页:

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace ClientAirNavLight_WS
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class MainPage : ClientAirNavLight_WS.Common.LayoutAwarePage
    {
        /// <summary>
        /// Represent a Web Service proxy.
        /// </summary>
        private AirNavLight_WSClientClient proxyWS;

        /// <summary>
        /// Initiialize the component of the application's main page.
        /// </summary>
        public MainPage()
        {
            this.InitializeComponent();          

        }



        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }


        //Simulate data update.
        private async void Button_Click(object sender, RoutedEventArgs e)
        {

            object selected = this.ListResult.SelectedItem;
            if (selected != null)
            {
                //simulate an update in data.
                // ListView should be refresh in order to reflect changes made here.
                Download dl = (Download)selected;
                if (dl.State == Download.DownloadState.Paused)
                {
                    dl.State = Download.DownloadState.Running;
                }
                else
                {
                    dl.State = Download.DownloadState.Paused;
                }

            }
            else
            {
                //Just add an item to the list view.
                StorageFile file = await this.getStorageFile("test");
                Download dl = new Download("192.128.2.14", file, "test", "1.2", 100, Protocol.HTTP);
                this.ListResult.Items.Add(dl);


                this.ListResult.DataContext = dl;// Does not work.


            }
        }


        private async Task<StorageFile> getStorageFile(String suggestedFileName)
        {
            FileSavePicker savePicker = new FileSavePicker();
            savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            // Dropdown of file types the user can save the file as
            savePicker.FileTypeChoices.Add("Application/pdf", new List<string>() { ".pdf" });
            savePicker.FileTypeChoices.Add("Archive", new List<string>() { ".zip", ".rar", ".7z" });
            savePicker.FileTypeChoices.Add("Plain-text", new List<string>() { ".txt" });
            // Default file name if the user does not type one in or select a file to replace
            savePicker.SuggestedFileName = suggestedFileName;
            return await savePicker.PickSaveFileAsync();
        }


    }
}

那么我应该如何使用 listView.DataContext 呢?我是否误解了如何使用 INotifyPropertyChanged?

编辑 :

我的 listView 是如何定义的:

 <ListView x:Name="ListResult" HorizontalAlignment="Left" Height="200" Margin="10,56,0,0" VerticalAlignment="Top" Width="653" SelectionMode="Single"/>
4

3 回答 3

3

你为什么要设置this.ListResult.DataContext = dl?在处理 ListView 时,ItemsSource 是所有被迭代的对象的集合,而不是 DataContext。此外,ItemsSource 应该是一个集合而不是一个项目。因此,如果您要绑定到某个属性,则该属性应该作为 ItemsSource 集合中的项目属性存在。

但是,看起来您没有集合,因此您将 dl 直接添加到 ListView 中this.ListResult.Items.Add(dl)。该方法应该有效,但是将this.ListResult.DataContext = dlor 设置this.ListResult.ItemsSource为集合并将 dl 添加到该集合

我不熟悉,[CallerMemberName]但如果您在 propertyName 为空时遇到问题,请尝试以下操作

    public DownloadState State
    {
        get{return this.state;}
        set {
            if( this.state != value )
            {
                this.state = value;
                NotifyPropertyChanged("State");
            }
        }
    }

此外,您要绑定的所有属性都应该是公共的并调用 NotifyPropertyChanged,如下所示

    private long totalSize ;

    public long TotalSize
    {
        get{return this.totalSize;}
        set {
            if( this.totalSize != value )
            {
                this.totalSize = value;
                NotifyPropertyChanged("TotalSize");
            }
        }
    }
于 2013-08-13T18:03:45.703 回答
3

在您的 Download 类中,唯一会在 UI 中更新的 Property 是 State,因为它有一个 getter 和 setter。

如果没有您的 XAML,则无法查看您要显示的内容,但通常情况下,您会将 DataContext 对象(在本例中为 dl)的属性绑定到列表视图随后可以显示的数据模板中的不同控件。

但是这些属性需要是公共的,并且有 INotifyPropertyChanged 的​​ getter 和 setter 来更新这些属性绑定到的 UI。

例如,如果您希望文件名显示在 ListView 中,则至少需要像这样声明文件名属性:

public String fileName {get; set; }
于 2013-08-13T17:47:55.160 回答
-1

Zangdak - 解决该问题的一种方法是,每次您的集合中的项目发生更改时,只需将 ListView 的 ItemSource 设置为 null,然后将其设置回您的集合。如果您这样做,UI 将更新,您将看到您的新项目已添加到您的收藏中。

佩奇·阿克

于 2015-03-26T21:17:11.560 回答