测试代码:public partial class Form1 : Form
    {
        public class Test : System.ComponentModel.INotifyPropertyChanged
        {
            private int m_Count = 0;
            public int Count
            {
                get { return m_Count; }
                set
                {
                    m_Count = value;
                    NotifyPropertyChanged("Count");
                }
            }            public void Begin()
            {
                Thread thread = new Thread(Counter);
                thread.Start();
            }            private void Counter()
            {
                for (int i = 0; i < 1000; i++)
                {
                    Count = i;
                    System.Threading.Thread.Sleep(100);
                }
            }            public void NotifyPropertyChanged(string info)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(info));
                }
            }            #region INotifyPropertyChanged 成员            public event PropertyChangedEventHandler PropertyChanged;            #endregion
        }        public Form1()
        {
            InitializeComponent();
            Binding binding = new Binding("Text", t, "Count");
            label1.DataBindings.Add(binding);
        }        Test t = new Test();        private void button1_Click(object sender, EventArgs e)
        {
            t.Begin();
        }    }代码当然是报错:线程间操作无效: 从不是创建控件“label1”的线程访问它。如果不用绑定的方式的话可以Invoke(xxxxx,xxxx)委托来修改控件的属性,但绑定时应该怎么委托呢???请教大伙。

解决方案 »

  1.   

    本帖最后由 bdmh 于 2012-05-22 15:36:37 编辑
      

  2.   

     public class Test : System.ComponentModel.INotifyPropertyChanged

      //加上这句先
     SynchronizationContext ctx = SynchronizationContext.Current;//后面在加上一些处理
    public void NotifyPropertyChanged(string info)
                {
                     //ctx==null表示非线程环境,直接使用标准方式处理
                      if (ctx == null)
                    {
                        PropertyChanged(this, new PropertyChangedEventArgs(info))                
                    }
                    else
                    {
                         //此处采用上下文同步方式发送消息,你当然也可以使用异步方式发送,异步方法为ctx.Post
                        ctx.Send(p => PropertyChanged(this, new PropertyChangedEventArgs(info)), null);                }  
                 }}
      

  3.   


    谢谢啊,但我这怎么SynchronizationContext.Current一直是空呢?
      

  4.   

    放到 Begin 方法的 thread.Start() 下一句, 成了 
      

  5.   

    还是悲催了,.Net Compact FrameWork 3.5里木有SynchronizationContext !!!
      

  6.   

                        
                public void Begin()
                {
                    ctx = SynchronizationContext.Current;
                    Thread thread = new Thread(Counter);
                    thread.Start();               
                }