1

我如何在调用位置获取从事件处理程序返回的值?我想做的是这样的

             ""  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;
                  }
4

1 回答 1

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

于 2012-11-01T12:36:56.537 回答