如何在调用位置获取从事件处理程序返回的值? 我想做的是这样的事情
"" int a = timer.Elapsed += new ElapsedEventHandler((sender, e) =>
on_time_event(sender, e, draw, shoul_l)); ""
timer_start = true;
timer.Interval = 2000;
timer.Start();
timer.Elapsed += new ElapsedEventHandler((sender, e) =>
on_time_event(sender, e, draw, shoul_l));
private int on_time_event(object sender, ElapsedEventArgs e,
DrawingContext dcrt, System.Windows.Point Shoudery_lefty)
{
.
.
.
.
return a_value;
}
答案 0 :(得分:1)
将值放在启动它的类的成员变量上。如果需要使用锁以允许安全的多处理。由于这是WPF,因此该类遵循INotifyPropertyChanged并将其绑定到屏幕上的控件。
编辑(根据OP的要求)
我会使用后台工作程序而不是计时器,但概念是相同的(要小心不要更新计时器中的GUI控件,但BW的设计允许这样做。)
public partial class Window1 : Window, INotifyPropertyChanged
{
BackgroundWorker bcLoad = new BackgroundWorker();
private string _data;
public string Data
{
get { return _data;}
set { _data = value; OnPropertyChanged("Data"); }
}
public Window1()
{
InitializeComponent();
bcLoad.DoWork += _backgroundWorker_DoWork;
bcLoad.RunWorkerCompleted += _backgroundWorker_RunWorkerCompleted;
bcLoad.RunWorkerAsync();
}
protected virtual void OnPropertyChanged( string propertyName )
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler( this, new PropertyChangedEventArgs( propertyName ) );
}
}
}
这是工作发生的地方
void _backgroundWorker_DoWork( object sender, DoWorkEventArgs e )
{
e.Result = "Jabberwocky";
}
这里是您为GUI安全设置值的地方。
void _backgroundWorker_RunWorkerCompleted( object sender, RunWorkerCompletedEventArgs e )
{
Data = (string) e.Result;
}
有关控件的另一个示例,请参阅我的博客:C# WPF: Threading, Control Updating, Status Bar and Cancel Operations Example All In One