Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

Delegate method to set the Text of a TextBlock

$
0
0

I have to ask a follow up qestion.
My previous question was this one:

In a WPF Navigation Page I have the following code:

         private void NewWindowHandler()
        {
            Thread newWindowThread = new Thread(new ThreadStart(ThreadStartingPoint));
            newWindowThread.SetApartmentState(ApartmentState.STA);
            newWindowThread.IsBackground = true;
            newWindowThread.Start();
        }
        
        private void ThreadStartingPoint()
        {
            PassingClass passingObj = new PassingClass() {
                FirstPar = "my first par", SecondPar= 123, ThirdPar = DateTime.Now, tb_Page2Callback = tb_Callback
            };
            Window1 tempWindow = new Window1(passingObj);
            tempWindow.Closed += (s,e) =>
            {
                Debug.WriteLine("CallBack: " + passingObj.CallBack );
                passingObj.handler(passingObj.CallBack, passingObj.tb_Page2Callback);
                Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Background);
            };
            tempWindow.Show();
            System.Windows.Threading.Dispatcher.Run();
        }

         public static void DelegateMethod(string message, TextBlock tb_Callback)
        {
            try {
                tb_Callback.Text = message;
            } catch (Exception exc) {
                Debug.WriteLine(exc.Message);
                Debug.WriteLine(exc.StackTrace);
            }
        }

and this is my PassingClass.cs

using System;
using System.Windows.Controls;

namespace SystemAlloc
{
    public delegate void Del(string message, TextBlock tb_Callback);
    public class PassingClass
    {
        public PassingClass()
        {
        }
        public string FirstPar;
        public int SecondPar;
        public DateTime ThirdPar;
        public string CallBack;
        public Del handler = Page2.DelegateMethod;
        public TextBlock tb_Page2Callback;
    }
}

How can I fix the Exception?

 CallBack: 3
The calling thread cannot access this object because a different thread owns it.
   at System.Windows.Threading.Dispatcher.VerifyAccess()
   at System.Windows.Threading.DispatcherObject.VerifyAccess()
   at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
   at System.Windows.Controls.TextBlock.set_Text(String value)
   at SystemAlloc.Page2.DelegateMethod(String message, TextBlock tb_Callback) 

Thank you!


Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>