将枚举值绑定到标签XAML

我正在使用Enum字段来跟踪我的程序状态。

public enum StatiMacchina { InAvvio = 1, Pronta = 2, InLavorazione = 3, InMovimento = 4, InAttesa = 5, InErrore = 6 } 

我想绑定跟随字段的状态(在主窗口中)

 public StatiMacchina StatoMacchina { get; set; } 

在XAML中带有标签。

  

我使用转换器(转换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"; } } 

当我的程序启动时,标签包含正确的值,但是当我更新StatoMacchina变量的状态时,标签不会得到刷新。 我能做什么??

现在你的UI无法知道任何事情都发生了变化。

您需要使用INotifyPropertyChaged 。 您应该从后面的代码中提取属性并将其放在ViewModel中,该ViewModel是窗口的DataContext。 ViewModel将实现INotifyPropertyChaged接口。 以下是实现INotifyPropertyChaged所需的全部内容。

 public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propName = null) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propName)); } } 

您需要展开属性的setter以设置值,然后触发OnPropertyChanged事件。 像这样……

 public StatiMacchina StatoMacchina { get; set{ backingVariable = value; OnPropertyChanged(); } } 

这将通过将您的xaml更改为此来触发您的UI可以侦听的事件。