Kamal Rathnayake
Kamal Rathnayake

Reputation: 582

The calling thread cannot access this object because a different thread owns it. Even after using dispatcher

In WPF I have this code:

wrapPanel.Dispatcher.Invoke(new Action(() =>
{
    wrapPanel.Children.Add(myCanvas);
}));

When i run this i get

"The calling thread cannot access this object because a different thread owns it"

As i know calling dispatcher.Invoke() should solve this problem.

Why am i getting this error? What are the possible reasons for this ?

Since my actual code is too long i didn't paste it all here. By the way I'm a noob.

Upvotes: 2

Views: 780

Answers (1)

Sheridan
Sheridan

Reputation: 69979

When using WPF, we work with data objects that are displayed by relating UI objects. Using Bindings, we update the UI by manipulating the data objects. I would implement something like this for your situation... first create a DependencyProperty in your MainWindow.cs to bind to:

public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register(
    "Items", typeof(ObservableCollection<Image>), typeof(MainWindow), 
    new UIPropertyMetadata(new ObservableCollection<Image>()));

public ObservableCollection<Image> Items
{
    get { return (ObservableCollection<Image>)GetValue(ItemsProperty); }
    set { SetValue(ItemsProperty, value); }
}

Then add the UI code that will display the data property:

<ItemsControl ItemsSource="{Binding Items}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

Finally, we must set the DataContext (this is the least preferable way to do it, but the simplest for this example):

public MainWindow()
{
    InitializeComponent();
    DataContext = this;
}

There is no need for any Dispatcher.Invoke calls to achieve this.

Upvotes: 1

Related Questions