Note that there are some explanatory texts on larger screens.

plurals
  1. POWindows Phone data binding: cross-thread
    text
    copied!<p>we have a problem with data binding on windows phone (using xaml). i have created a simple example, which should allow to reproduce the problem. Here is our model-class:</p> <pre><code>public class Data : INotifyPropertyChanged { private int value = 0; public int Value { get { return value; } set { this.value = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Value")); } } } public event PropertyChangedEventHandler PropertyChanged; public Data() { var t = new Thread(new ThreadStart(() =&gt; { while (true) { Thread.Sleep(2000); Value += 1; } })); t.IsBackground = true; t.Start(); } } </code></pre> <p>which uses a thread to update the value-property and fire the PropertyChanged-event.</p> <p>Now i want to bind this value-property to a gui control:</p> <pre><code> &lt;Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"&gt; &lt;TextBlock Text="{Binding Path=Value}" /&gt; &lt;/Grid&gt; public MainPage() { InitializeComponent(); DataContext = new Data(); } </code></pre> <p>when the value first changes (and the PropertyChanged-event gets fired) the data binding system tries to copy the value of Data.Value to TextBlock.Text, which results in an invalid cross-thread exception, as this event is not fired on the ui thread.</p> <p>my question: shouldn't the .NET databinding framework recognize that i'm binding to a ui control and perform the thread switching itself? i know that i can simply use a dispatcher to fire the PropertyChanged-event on the main thread, but i'd like to have my model-class more seperated from the gui component. is there a better solution to this problem? i am unable to use the DependencyObject approach, because our core project (which contains the model class) should run on Windows Phone AND Android, and Android doesn't support the System.Windows-namespace.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload