Home > OS >  How to access UI elements in multiple threads?
How to access UI elements in multiple threads?

Time:10-06

I had a standard foreach loop which I later turned into a Parallel.Foreach(). However in my loop I have areas where I access the UI elements and get and set the UI elements info.

So when I run it I get an error that I cannot access the element as another thread has access to it. There are multiple elements I need to access and the x:Name are stored in the list.

How do I get past this?

Parallel.ForEach(calculatedTestVariables, variable =>
        {
            string idName = "id_"   variable.id;
            var textBox = this.FindName(idName) as TextBox; //need the text from this TextBox

            //some calculations
            int x = 1   2   3   4

            textBox.Text = x.toString();

        });

CodePudding user response:

To do this, you need data binding. You may follow such a way,

First create your view model and update your properties:

public class MainViewModel : BindableBase
{
    private string m_TextProgress;
    public string TextProgress
    {
        get { return m_TextProgress; }
        set { SetProperty(ref m_TextProgress, value); }
    }

    public void Run()
    {
        List<Variable> calculatedTestVariables = new List<Variable>();

        for (int i = 0; i < 5000; i  )
        {
            Variable item = new Variable();

            item.id = i;
            calculatedTestVariables.Add(item);
        }

        Parallel.ForEach(calculatedTestVariables, variable =>
        {
            string idName = "id_"   variable.id;

            //some calculations
            int x = 1   2   3   4;

            TextProgress = ""   variable.id   x;
        });
    }
}

Set your DataContext

<Window.DataContext>
    <local:MainViewModel />
</Window.DataContext>

<Grid>

    <StackPanel>
        <TextBlock
            Width="120"
            Height="30"
            HorizontalAlignment="Left"
            VerticalAlignment="Top"
            Text="{Binding TextProgress, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}" />

        <Button
            Width="120"
            Height="30"
            HorizontalAlignment="Left"
            VerticalAlignment="Top"
            Click="Button_Click"
            Content="Calculate" />
    </StackPanel>
</Grid>

and call your Run method from GUI side

enter image description here

  • Related