Bill Gates
Bill Gates

Reputation: 857

WPF UI Threading

I am trying to update chart and draw some scatter points there. For that I am using BackgroundWorker class. It does job. But I noticed as soon as I add color to my Point class and want display points of different colors it crashes. Why? any ideas?

    public class ChartData
    {
        private readonly Brush Red = new SolidColorBrush(Colors.Red);
        private readonly Brush Orange = new SolidColorBrush(Colors.Orange);
        private readonly Brush Green = new SolidColorBrush(Colors.Green);

        public ChartData(double x, double y)
        {
            this.XValue = x;
            this.YValue = y;
        }

        public double XValue { get; set; }
        public double YValue { get; set; }

        public Brush Brush{ get; set;}
    }

    <telerik:ScatterPointSeries XValueBinding="XValue" 
                            YValueBinding="YValue" 
                            ItemsSource="{Binding Data}" >
        <telerik:ScatterPointSeries.PointTemplate>
            <DataTemplate>
                <Ellipse Width="10"
             Height="10"
             Fill="{Binding DataItem.Brush}"/>
            </DataTemplate>
        </telerik:ScatterPointSeries.PointTemplate>
    </telerik:ScatterPointSeries>

Exception: Must create DependencySource on same Thread as the DependencyObject.

Upvotes: 2

Views: 944

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81243

As stated in the message itself, you can't modify DependencySource(add,create,delete) from antoher thread. You can modify it from same thread which is in your case is UI thread.

As a way out you can put the code of modifying dependency source on UI thread dispatcher

App.Current.Dispatcher.Invoke((Action)delegate()
            {
                // Code here for updating Dependency Source.
            });

Upvotes: 1

Related Questions