测试代码: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)委托来修改控件的属性,但绑定时应该怎么委托呢???请教大伙。
{
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)委托来修改控件的属性,但绑定时应该怎么委托呢???请教大伙。
{
//加上这句先
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); }
}}
谢谢啊,但我这怎么SynchronizationContext.Current一直是空呢?
public void Begin()
{
ctx = SynchronizationContext.Current;
Thread thread = new Thread(Counter);
thread.Start();
}