C # data binding does not update WPF

I am trying to bind data in C # code, not in XAML. The XAML binding created in Expression Blend 2 with my CLR object works fine. My C # implementation is only updated when the application starts, after which subsequent changes to the CLR do not update the contents of my label.

Here's the working XAML binding. First, an ObjectDataProvider is created in my Window.Resources.

<ObjectDataProvider x:Key="PhoneServiceDS" ObjectType="{x:Type kudu:PhoneService}" d:IsDataSource="True"/> 

And binding the contents of the label:

 <Label x:Name="DisplayName" Content="{Binding Path=MyAccountService.Accounts[0].DisplayName, Mode=OneWay, Source={StaticResource PhoneServiceDS}}"/> 

It works great. But we want this to be configured in C # so that we can independently modify the XAML (i.e. new skins). My one-time working C # looks like this:

  Binding displayNameBinding = new Binding(); displayNameBinding.Source = PhoneService.MyAccountService.Accounts[0].DisplayName; displayNameBinding.Mode = BindingMode.OneWay; this.DisplayName.SetBinding(Label.ContentProperty, displayNameBinding); 

This is inside my MainWindow after InitializeComponent ();

Any insight into why this only works on startup?

+4
source share
3 answers

Your C # version does not match the XAML version. It should be possible to write a code version of your markup, although I'm not familiar with ObjectDataProvider.

Try something like this:

 Binding displayNameBinding = new Binding( "MyAccountService.Accounts[0].DisplayName" ); displayNameBinding.Source = new ObjectDataProvider { ObjectType = typeof(PhoneService), IsDataSource = true }; displayNameBinding.Mode = BindingMode.OneWay; this.DisplayName.SetBinding(Label.ContentProperty, displayNameBinding); 
+3
source

In the source code, you confuse the source and the path.

  Binding displayNameBinding = new Binding(); displayNameBinding.Source = PhoneService; displayNameBinding.Path = "MyAccountService.Accounts[0].DisplayName"; displayNameBinding.Mode = BindingMode.OneWay; this.DisplayName.SetBinding(Label.ContentProperty, displayNameBinding); 

(I assume that PhoneService is an instance of the object, otherwise, perhaps PhoneService. MyAccountService.Accounts [0] should be the source?)

From memory, you can pass the path as an argument to the constructor.

+1
source

Write this inside the loaded event instead of the constructor. Hope you turned on the INotifyPropertyChanged function running in the DisplayName Property Customizer?

0
source

All Articles