0

我创建了一个 wpf 应用程序。其中有一个复选框和两个用于启动和停止计时器的按钮。单击启动按钮 System.Timers.Timer 后,aTimer 将开始运行并调用方法 checkboxstatus() 以获取复选框状态并将其显示给用户。即使选中了复选框,我也会收到消息为 False。我使用了以下代码

public partial class MainWindow : Window
{  
    System.Timers.Timer aTimer = new System.Timers.Timer();
    bool ischeckboxchecked = false;

    public MainWindow()
    {
        InitializeComponent();
        aTimer.Elapsed += new ElapsedEventHandler(senddata_Tick);
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        aTimer.Interval = 3000;
        aTimer.Start();
    }
    public string checkboxstatus()
    {
        string data = string.Empty;
        ischeckboxchecked = false;
        Dispatcher.BeginInvoke((Action)(() =>
        {
            if (checkBox1.IsChecked == true)
            {
                ischeckboxchecked = true; //value is updating on each timer tick
            }
        }));
        data += ischeckboxchecked.ToString();
        return data;
    }
    private void senddata_Tick(Object sender, EventArgs args)
    {
        string postdata = string.Empty;
        postdata = checkboxstatus(); //every time am getting data as false
        MessageBox.Show(postdata);
    }
    private void button2_Click(object sender, RoutedEventArgs e)
    {
        aTimer.Stop();
    }

    private void checkBox1_Checked(object sender, RoutedEventArgs e)
    {

    }
}

任何人建议.......

4

1 回答 1

1

您正在使用您的方法调用BeginInvoke调度程序。BeginInvoke立即返回。Invoke改为获取阻塞调用并仅在操作Dispatcher完成后返回。

于 2014-07-03T14:26:58.440 回答