user3363744
user3363744

Reputation: 169

C# Custom Event In Class not updating Textbox

I have an issue with my custom event not updating a text box on my UWP application. If I replace the Textbox1.Text with debug.Writeline it works. Is there a reason why I can't update a textbox using an event? If I use the Progress object it works. I am just trying to figure out why it wouldnt work with my own custom event. Thank you

 public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }

    private void button_click(object sender, RoutedEventArgs e)
    {
        recData myRecDataobject = new recData();
        myRecDataobject.dataRecvEvent += () =>
        {
            textBox2.Text = "Event Occured"; // This throws an error
            Debug.WriteLine("test2");
        };

        Progress<int> progress = new Progress<int>();
        myRecDataobject.getDataMethodAsync(progress);
        progress.ProgressChanged += (o, result) =>
        {
            textBox1.Text = result.ToString();

        };

    }

}

public class recData
{
    public delegate void myEvenetHandlerDelegate();
    public event myEvenetHandlerDelegate dataRecvEvent;


    private int _myValue;
    public int myValue
    {
        get
        {
            return _myValue;
        }
        set
        {
            _myValue = value;
        }
    }

    public async void getDataMethodAsync(Progress<int> progress)
    {
        await getDataMethod(progress);
    }

    private Task getDataMethod(IProgress<int> progress)
    {
        return Task.Factory.StartNew(() =>
        {
            for (int i = 0; i < 1000; i++)
            {
                Task.Delay(2000).Wait();
                if (dataRecvEvent != null)
                {
                    dataRecvEvent();
                    progress.Report(i);
                }

            }

        });
    }


}

Upvotes: 0

Views: 123

Answers (1)

Peter Torr
Peter Torr

Reputation: 12019

You are trying to update a XAML property from a background thread. This doesn't work (your error should be "access denied").

Use Dispatcher.BeginInvoke to schedule the TextBox property update on the UI thread.

Upvotes: 1

Related Questions