tags:

views:

111

answers:

3

Hi there,

I want to bind some properties from my code-behind .xaml.cs to some xaml-code, just like this:

<TextBlock [someProperties] ... Text="{Binding ElementName=awesome, Path=value}" />
<TextBlock [someProperties] ... Text="{Binding Path=legendary}" />

In the associated .xaml.cs file I have the property:

public String legendary = "High five";
public CoolObject awesome = new CoolObject(); //has a public property "String value = '5';"

But my TextBlocks just don't want to show that damn "High five" and "5". What am I missing?

A: 

The problem is that "legendary" and "awesome" are declared as fields not properties. WPF binding will not work with fields.

Daniel Pratt
A: 

You'll need to wrap your fields with properties. Binding doesn't support fields.

So:

public String _legendary = "High five";
public String legendary {
    get { return _legendary; }
    set { _legendary = value; }
 }

Also, if you might want to look into implementing INotifyPropertyChanged to make sure whatever you're binding to your property gets updated when you change the value of the property.

Mark Synowiec
Still doesn't work.. have declared legendary as follow, just to try: public String legendary { get { return "High Five";} set {} }
Thomas
A: 

And <TextBlock [someProperties] ... Text="{Binding ElementName=awesome, Path=value}" /> will not work. ElementName is used, when you want to bind to some elemnt's in visual tree property. You need

<TextBlock [someProperties] ... Text="{Binding Path=awesome.value}" />

Also you need to set TextBlock's DataContext property to bject that contains properties you need to bind.

Yurec
Thanks, setting the DataContext plus setting the properties as properties, not fields, did it. YAY!
Thomas
you are welcome
Yurec