C#Windows表单应用程序进度条dataBinding

时间:2014-03-19 09:50:54

标签: c# winforms data-binding progress-bar

我正在开发一个C#Windows窗体应用程序,我在其中放置了一个ProgressBar,我希望将其绑定到我的类的属性。下面的代码不起作用,但我不知道为什么......

    public int MyProperty
    {
        get { return device.Perc;  }
        set 
        { 
            device.Perc = value;
            NotifyPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public FormFULProgress()
    {
        InitializeComponent();

        progressBar1.Maximum = 100;

        progressBar1.DataBindings.Add("Value", this, "MyProperty");
    }

1 个答案:

答案 0 :(得分:1)

这有效:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class FormFULProgress : Form, INotifyPropertyChanged
    {
        private int Perc = 50;

        public FormFULProgress()
        {
            InitializeComponent();

            progressBar1.Maximum = 100;

            progressBar1.DataBindings.Add("Value", this, "MyProperty");
        }

        public int MyProperty
        {
            get { return Perc; }
            set
            {
                Perc = value;
                OnPropertyChanged("MyProperty");
            }
        }

        // Declare the event 
        public event PropertyChangedEventHandler PropertyChanged;

        // Create the OnPropertyChanged method to raise the event 
        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.MyProperty = 75;
        }

    }
}