0

I have this Model:

class Person
{
    public static int Counter;
    public string _firstName;
    public string _lastName;

   public string FirstName
   {
        get {return _firstname; }
        set
        {
            _fileName = value;               
        }
   }

   public AddPerson(Person person)
   {
       Counter++;
   }
}

Now i try to binding My Counter property into simple TextBlock:

<TextBlock Name="tbStatusBar" Text="{Binding Person,Source={StaticResource Person.Counter}}" />

And got this error: The recourse Person.Counter could not be resolved.

roz wer
  • 101
  • 1
  • 2
  • 8
  • you could do `Text="{Binding Source={x:Static local:Person.Counter}}"` but it won't auto refresh as you won't implement `INotifyPropertyChanged` for static properties/fields – dkozl Jul 12 '15 at 17:53
  • I have updated my answer to provide an alternate binding scenario. Long story short, you will need at least one object available to the visible or logical tree to ultimately bind `Counter` to... – ΩmegaMan Jul 12 '15 at 20:03

1 Answers1

-1

Binding requires properties and not fields. Change Counter to be a property and bind to it directly such as

Text="{Binding Counter}"

Binding in Xaml requires an item on the visual or logical tree to actually bind off of. See Trees in WPF. The static property Counter exists but not in a location where binding can find it.

So either create a Person object on the page's resources (you may need to make the Person class public so the namespace resolution can find it) such as:

<local:Person x:Key="myPerson"/>

and bind to it such as

<TextBlock Text="{Binding Count}"
           DataContext="{Binding Source={StaticResource myPerson}}">

Or if the TextBlock's data context has access to one of them such as a valid (non null) List of Person objects (for this example) called 'Persons' as shown below:

<TextBlock DataContext="{Binding Persons[0]}" Text="{Binding Counter}"/>
ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122