Why isn't Dispatcher.BeginInvoke working when re-creating my WPF DataGrid columns?
<p>I have a <code>DataGrid</code> with a set of columns dynamically generated for a range of dates, and bound to the grid with a custom dependency property, </p>

<pre><code>public static readonly DependencyProperty BindableColumnsProperty =
    DependencyProperty.RegisterAttached("BindableColumns",
        typeof(ObservableCollection&lt;DataGridColumn&gt;),
        typeof(DataGridAttachedProperties),
        new UIPropertyMetadata(null, BindableColumnsPropertyChanged));
</code></pre>

<p>The <code>BindableColumnsPropertyChanged</code> contains the following code that is where the problems occur:</p>

<pre><code>else if (ne.Action == NotifyCollectionChangedAction.Add)
{
    foreach (DataGridColumn column in ne.NewItems)
    {
        dataGrid.Columns.Add(column);
    }
}
else if (ne.Action == NotifyCollectionChangedAction.Remove)
{
    foreach (DataGridColumn column in ne.OldItems)
    {
        dataGrid.Columns.Remove(column);
    }
}
</code></pre>

<p>When I call my <code>InitColumns</code> method from the <code>RefreshCommand</code> code, on <code>dataGrid.Columns.Remove(column)</code> I get the error:</p>

<blockquote>
  <p>The calling thread cannot access this object because a different
  thread owns it.
  I fixed that by changing the <code>Remove</code> code to:</p>
</blockquote>

<pre><code>Application.Current.Dispatcher.BeginInvoke((Action)(() =&gt;
{
    dataGrid.Columns.Remove(column);
}));
</code></pre>

<p>Then I try again, and the <code>Remove</code> code works, but I obviously get the same error on the <code>dataGrid.Columns.Add(column)</code> line. I also change that:</p>

<pre><code>Application.Current.Dispatcher.BeginInvoke((Action)(() =&gt;
{
    dataGrid.Columns.Add(column);
}));
</code></pre>

<p>And I try running the refresh command again, again the new dispatched <code>Remove</code> still works, but now I get the same error, but withing the <code>BeginInvoke</code> delegate for the <code>dataGrid.Columns.Add(column)</code> call:</p>

<p><a href="https://i.stack.imgur.com/lCkkr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lCkkr.png" alt="enter image description here"></a></p>

<p>This I don't understand. It is surely the same thread that successfully removed the column, but now it looks like some new phantom thread is trying to add the column. Whatever could cause this?</p>