views:

212

answers:

2

Hi there,

I'm making an application and I'm using a timer in that application to change label content in WPF C# .NET.

In timer elapsed event I'm writing the following code

lblTimer.Content = "hello";

but its throwing an InvalidOperationException and gives a message "The calling thread cannot access this object because a different thread owns it."

I'm using .NET framework 3.5 and WPF with C#.

Please help me. Thanks in advance.

A: 

lblTimer was declared in your main, GUI thread, and you are trying to update it from a different thread -> you get this error.

This link "Accessing WPF controls on a non UI Thread" contains a description of your problem and a fix for it.

Ando
Thanks Ando, Thats working....Keep it up!!
Guru
You're welcome ;)
Ando
A: 

InvokeRequired doesn't work in wpf.

The proper way the update a GUI element owned by another thread is this :

Declare this on module level :

delegate void updateLabelCallback(string tekst);

This is the method to update your label :

private void UpdateLabel(string tekst)
    {
        if (label.Dispatcher.CheckAccess() == false)
        {
            updateLabelCallback uCallBack = new updateLabelCallback(UpdateLabel);
            this.Dispatcher.Invoke(uCallBack, tekst);
        }
        else
        { 
    //update your label here
        }
     }
djerry