I'm using a Enum field to follow the state of my program.
public enum StatiMacchina {
InAvvio = 1,
Pronta = 2,
InLavorazione = 3,
InMovimento = 4,
InAttesa = 5,
InErrore = 6
}
I would to bind the state of the follow field (in the main window)
public StatiMacchina StatoMacchina { get; set; }
with a label in XAML.
<TextBlock Text="{Binding Path=StatoMacchina, Converter={StaticResource StatoMacchinaToString}}" />
I use a converter (below the Convert function)
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
switch ((StatiMacchina)value) {
case StatiMacchina.InAvvio: return "txt1";
case StatiMacchina.Pronta: return "txt2";
case StatiMacchina.InLavorazione: return "txt3";
case StatiMacchina.InMovimento: return "txt4";
case StatiMacchina.InAttesa: return "txt5";
case StatiMacchina.InErrore: return "txt6";
default: return "Oppss";
}
}
When my program start the label contains the correct value, but when I update the state of the StatoMacchina variable, the label doesn't get the refresh. What can I do??
Right now your UI has no way of knowing that anything has changed.
You need to use INotifyPropertyChaged. You should pull the property from your code behind and put it in a ViewModel that is the DataContext of your window. That ViewModel will implement the interface INotifyPropertyChaged. Below is all you need to implement INotifyPropertyChaged.
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propName = null)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
You need to expand the setter of your property to set the value then fire an OnPropertyChanged event. like so..
public StatiMacchina StatoMacchina {
get;
set{
backingVariable = value;
OnPropertyChanged();
}
}
This will fire an event that your UI can listen for by changing your xaml to this.
<TextBlock Text="{Binding Path=StatoMacchina, Converter={StaticResource StatoMacchinaToString}, UpdateSourceTrigger=PropertyChanged}" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With