简体   繁体   中英

WPF real time refresh text data

I am trying to demonstrate file transfer in WPF so that it refreshes the screen in real time and shows the current data. My requirement is it should show the current file which is being transferred. This is my code I have written.

public MainWindow()
        {
            InitializeComponent();
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += tick_event;
            timer.Start();
        }

        private void tick_event(object sender, EventArgs e)
        {
            for (int i = 0; i < 60; i++)
            {
                txtName.Text = "Transfering file no. "+i.ToString();
            }          
        }

what I have tried is for instance there are 60 files and the screen show me which file is being transferred. But, when I run this code it shows me only the last file which is 59th file. What changes I can make here to make this work? Thanks in advance.

When you say

it shows me only the last file which is 59th file

It is because when the event triggers it counts from 0 to 59 and it writes those numbers with no delay into txtName . The consecuence is that you only see the latest written number.

You should set a counter and in the timer event only write the counter variable.

DispatcherTimer timer = new DispatcherTimer();
private int filesCopied = 0;

public MainWindow()
{
    InitializeComponent();
    
    timer.Interval = TimeSpan.FromSeconds(1);
    timer.Tick += tick_event;
    timer.Start();
}

private void tick_event(object sender, EventArgs e)
{
   filesCopied++;
   txtName.Text = "Transfering file no. " + filesCopied.ToString();
   if (filesCopied >= 60) timer.Stop();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM