Dear reader,
Im having a threading problem using WPF data binding on a custom
dependency object with a clr object as data source and trying to
update the data source from another execution context. The data source
consists out of a simple class which implements the
INotifyPropertyChanged interface.
<code>
// The clr object used as a data source.
public class MyDataSource : INotifyPropertyChanged
{
private string _data;
public MyDataSource(string info)
{
_data = data;
}
public string Data
{
get
{
return _data;
}
set
{
_data = value;
this.NotifyPropertyChanged(value);
}
}
private void NotifyPropertyChanged(string data)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(data));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
</code>
The custom dependency object exposes one dependency property which I
want to bind to the Data property of the data source. Below the code
for illustration:
<code>
// the custom dependency object.
public class MyCustomObject : DependencyObject
{
public static readonly DependencyProperty DataProperty =
DependencyProperty.Register("DataProperty", typeof(String),
typeof(MyCustomObject), new PropertyMetadata(String.Emoty, new
PropertyChangedCallback(OnPropertyChanged)));
public static void OnPropertyChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
MyCustomObject obj = (MyCustomObject) d;
Console.WriteLine(String.Format("Property '{0}' changed; OldValue
'{1}', NewValue '{2}'.", e.Property.Name, e.OldValue, e.NewValue));
}
public MyCustomObject()
{ }
public string Data
{
get
{
return (string)this.GetValue(DataProperty);
}
set
{
this.SetValue(DataProperty, value);
}
}
}
</code>
And finally the binding definition:
<code>
MyDataSource dataSource = new MyDataSource("Hello World!");
MyCustomObject customObj = new MyCustomObject();
Binding binding = new Binding("Data");
binding.Mode = BindingMode.OneWay;
binding.Source = dataSource;
BindingOperations.SetBinding(customObj, MyCustomObject.DataProperty,
binding);
...
// Causes the dependency property to change.
dataSource.Data = "Greetings World!";
</code>
The above code works fine. But when I try to update the "dataSource"
object from a WCF service callback (duplex mode) it doesn't update the
dependency property. I think it as something to do with the execution
context being different. Can anybody shed some light on this matter
and explain me why this binding doesn't work this way and maybe come
up with a solution.
I'm running the above code within a console application (STA) compiled
with the .NET Framework 3.5 version in Visual Studio 2008.
Kind regards,
Alex Koning.