Yaron
Yaron

Reputation: 233

Strange Threads behavior

.Hi, I have some problem with wpf and threading, and I just can't understend what happaning here.

I have this event func

private void TaskActiveChangeClicked(object sender, RoutedEventArgs e)
{
   //Do things...
   this.ChangeTask((sqTask)this.SelectionObject, (sqTask)this.SelectionObject);
   this.FindSelectionObject();
}

ChangeTask

private void ChangeTask(sqTask Old, sqTask New)
{            
    //Do things (update in mongoDB)...
    this.LoadTaskList();
}

LoadTaskList [TaskListTable is a DataGrid]

private void LoadTaskList()
{
    //Do things (query mongoDB and get List<sqTask>)...
    this.Dispatcher.Invoke((Action)(() =>
    {
        TaskListTable.Items.Clear();
        foreach (sqTask task in TaskList)
        {
            TaskListTable.Items.Add(db);
        }
    }                
    ));
}

And now the weird part...

The SelectedIndex binding to TaskListTable DataGrid (SelectedIndex="{Binding SelectedIndex}")

When I Run FindSelectionObject() just like this:

private void FindSelectionObject()
{
    this.SelectedIndex = TaskListTable.Items.IndexOf(((sqTask)SelectionObject));
    MessageBox.Show("");
    DataGridRow row = TaskListTable.ItemContainerGenerator.ContainerFromItem(TaskListTable.Items[SelectedIndex]) as DataGridRow;                        
    row.Background = Brushes.LightGoldenrodYellow
}

it works perfectly, but if I remove the MessageBox it crash becuase row not contains instance

I guesss that LoadTaskList adding the items to the DataGrid, but it dons't update until the call end. therefor, ...ContainerFromItem(TaskListTable.Items[SelectedIndex]) as DataGridRow; is empty.

But when I use the messageBox, it makes the thred do some "Tick" before it search the row in the table.

Questions: Am i right? and how can I fix it? (btw, If you can add to the answer recommended guide for theads use i'll be glad)

Thanks!

Upvotes: 1

Views: 68

Answers (1)

It&#39;sNotALie.
It&#39;sNotALie.

Reputation: 22814

It is because while you show the box, the TaskListTable gets all its items added. If you put a dummy Thread.Sleep there instead, it would work.

Upvotes: 1

Related Questions