Reputation: 6450
I wonder how to update my UI
with my static
property.
I have 2 properties in my model and one of them is static
:
public class Machine : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public static event PropertyChangedEventHandler StaticPropertyChanged;
public string _name;
public static int _counter;
public void AddMachine(Machine machine)
{
_counter++;
}
public string Name
{
get { return _name; }
set
{
_name = value;
NotifyPropertyChange("Name");
}
}
public static int Counter
{
get { return _counter; }
set
{
_counter = value;
OnStaticlPropertyChanged("Counter");
}
}
public virtual void NotifyPropertyChange(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
public static void OnStaticlPropertyChanged(string propertyName)
{
var handler = StaticPropertyChanged;
if (handler != null)
StaticPropertyChanged(
typeof(Machine),
new PropertyChangedEventArgs(propertyName));
}
}
As you can see i created another PropertyChangedEventHandler
for my static
value.
The other property (not the static one - Name) is working fine.
I am holding my object in collection:
public ObservableCollection<Machine> machines { get; set; }
And i can see the Counter
is changing but not updating my UI
, this is how i am trying to update my UI
using TextBlock
:
<TextBlock Name="tbStatusBar" Text="{Binding Source={x:Static my:Machine.Counter}}" />
So my question is what am I doing wrong ?
Upvotes: 0
Views: 232
Reputation: 128061
First, you have to make sure to use WPF 4.5, as the StaticPropertyChanged
event mechanism won't work with an older version.
Then, in AddMachine
, you should update the property, not its backing field:
public void AddMachine(Machine machine)
{
Counter++;
}
Finally, you have to change the binding expression from a static source to a path to a static property (note the parenthesis):
<TextBlock Text="{Binding Path=(my:Machine.Counter)}" />
Upvotes: 1