当属性在类中更改时,如何在表单中接收属性更改通知?

时间:2011-07-27 11:10:28

标签: c# .net wpf .net-4.0 inotifypropertychanged

我有一个带有INotifyPropertyChanged接口的类。有一个名为Total Progress的财产。

我有一个带有进度条的表单。我想将TotalProgress属性更改通知发送到此进度条并设置它的值。

我是否还需要在表单中捕获PropertyChangedEvent?

编辑:WPF表单代码

using System.ComponentModel;
using System.Windows;
using System.Windows.Data;
using System;
using System.Windows.Threading;

namespace SUpdater
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        BackgroundWorker bw = new BackgroundWorker();
        DownloadFile FileDownloadClass = new DownloadFile();

        public MainWindow()
        {
            InitializeComponent();

            bw.WorkerReportsProgress = true;
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);

            progressBar1.SetBinding(System.Windows.Controls.ProgressBar.ValueProperty, new Binding("TotalPercentCompleted"));
            progressBar1.DataContext = FileDownloadClass;

            FileDownloadClass.PropertyChanged +=new PropertyChangedEventHandler(FileDownloadClass_PropertyChanged);
        }

        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            FileDownloadClass.DownloadFiles();

            if ((bw.CancellationPending == true))
                e.Cancel = true;
            else
            {
                bw.ReportProgress(FileDownloadClass.TotalPercentCompleted);
            }

        }

        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if ((e.Cancelled == true))
            {
                this.lblConnectionStatus.Content = " Download Canceled!";
            }

            else if (!(e.Error == null))
            {
                this.lblConnectionStatus.Content = ("Error: " + e.Error.Message);
            }

            else
            {
                this.lblConnectionStatus.Content = "Done!";
            }
        }

        private void FileDownloadClass_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {

        }

        private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            lblKbCompleted.Content = e.ProgressPercentage.ToString();

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            bw.RunWorkerAsync();
        }

    }
}

编辑:DownloadFile类代码

    sealed class DownloadFile:INotifyPropertyChanged
    {

        #region Private Fields
            // These fields hold the values for the public properties.
            private int progressBarValue = 0;
            private int totalKbCompleted = 0;
            private int totalBytesReceived = 0;
            private int remoteFileSize = 0;

            private string fileName = String.Empty;
            private string statusMessage = String.Empty;
        #endregion

            public event PropertyChangedEventHandler PropertyChanged;

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

            #region Public Properties
            public int TotalKbCompleted
            {
                get { return this.totalKbCompleted; }

                set
                {
                    if (value != this.totalKbCompleted)
                    {
                        this.totalKbCompleted = value/1024;
                        NotifyPropertyChanged("TotalKbCompleted");
                    }
                }                
            }

            public int TotalBytesReceived
            {
                get { return this.totalBytesReceived; }

                set
                {
                    if (value != this.totalBytesReceived)
                    {
                        this.totalBytesReceived = value;
                        NotifyPropertyChanged("TotalBytesReceived");
                    }
                }
            }

            public int RemoteFileSize
            {
                get { return this.remoteFileSize; }

                set
                {
                    if (value != this.remoteFileSize)
                    {
                        this.remoteFileSize = value;
                        NotifyPropertyChanged("RemoteFileSize");
                    }
                }
            }

            public string CurrentFileName
            {
                get { return this.fileName; }

                set
                {
                    if (value != this.fileName)
                    {
                        this.fileName = value;
                        NotifyPropertyChanged("CurrentFileName");
                    }
                }
            }

            public string StatusMessage
            {
                get { return this.statusMessage; }

                set
                {
                    if (value != this.statusMessage)
                    {
                        this.statusMessage = value;
                        NotifyPropertyChanged("StatusMessage");
                    }
                }
            }
            #endregion

        public Int16 DownloadFiles()
        {
            try
            {

                statusMessage = "Attempting Connection with Server";

                DoEvents();
                // create a new ftpclient object with the host and port number to use
                FtpClient ftp = new FtpClient("mySite", 21);

                // registered an event hook for the transfer complete event so we get an update when the transfer is over
                //ftp.TransferComplete += new EventHandler<TransferCompleteEventArgs>(ftp_TransferComplete);

                // open a connection to the ftp server with a username and password
                statusMessage = "Connected. Authenticating ....";
                ftp.Open("User Name", "Password");

                // Determine File Size of the compressed file to download
                statusMessage = "Getting File Details";
                RemoteFileSize = Convert.ToInt32(ftp.GetFileSize("myFile.exe"));

                ftp.TransferProgress += new EventHandler<TransferProgressEventArgs>(ftp_TransferProgress);
                statusMessage = "Download from Server";
                ftp.GetFile("myFile.exe", "E:\\Test\\myFile.exe", FileAction.Create);

                // close the ftp connection
                ftp.Close();
                statusMessage = "Download Complete";
                return 1;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
                return 0;
            }

        }


        private void ftp_TransferProgress(object sender, TransferProgressEventArgs e)
        {
            totalBytesReceived = Convert.ToInt32(e.BytesTransferred.ToString());
            totalKbCompleted = Convert.ToInt32(totalKbCompleted + Convert.ToInt32(totalBytesReceived));
            progressBarValue = totalKbCompleted;
        }
}

1 个答案:

答案 0 :(得分:4)

您可以使用控件绑定:

Windows窗体:

progressBar1.DataBindings.Add("Value", dataSource, dataMember, true,
    DataSourceUpdateMode.OnPropertyChanged);

dataSource是你的班级。并且dataMember是该类“TotalProgress”中的属性名称。

修改:对于 WPF

progressBar1.SetBinding(ProgressBar.ValueProperty, new Binding("ProgressTotal"));
progressBar1.DataContext = the instance of the class you want to bind to its property;

有关wpf数据绑定的详细信息,请检查thisthis

Edit2:以下是一个完整的示例:

Foo _foo = new Foo();

DispatcherTimer _dispatcherTimer = new DispatcherTimer();

public MainWindow()
{
    InitializeComponent();

    _dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
    _dispatcherTimer.Tick += _dispatcherTimer_Tick;
    _dispatcherTimer.Start();

    progressBar1.SetBinding(ProgressBar.ValueProperty, new Binding("ProgressTotal"));
    progressBar1.DataContext = _foo;
}

private void _dispatcherTimer_Tick(object sender, EventArgs e)
{
    _foo.ProgressTotal = (_foo.ProgressTotal + 10) % progressBar1.Maximum;
}


public class Foo : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private double _progressTotal = 0;

    public double ProgressTotal
    {
        get { return _progressTotal; }
        set 
        {
            if (value != _progressTotal)
            {
                _progressTotal = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("ProgressTotal"));
                }
            }
        }

    }
}

编辑:添加计时器以预览效果。

修改:上传代码后,问题会出现在两个位置:

  1. 变量的名称为TotalKbCompletedTotalPercentCompleted。所以将绑定线更改为:

    progressBar1.SetBinding(System.Windows.Controls.ProgressBar.ValueProperty, new Binding("TotalKbCompleted"));
    
  2. 您正在更新totalKbCompleted而不是TotalKbCompleted,因此更改的属性不会触发。