2015-07-13 186 views
0

我不知道如何更新我的UI与我的static属性。 我在我的模型2个属性和其中一个staticPropertyChangedEventHandler静态变量不变

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)); 
    } 
} 

正如你可以看到我为我的static值创造了另一个PropertyChangedEventHandler。 其他属性(不是静态的 - 名称)工作正常。 我捧在收集我的对象:

public ObservableCollection<Machine> machines { get; set; } 

,我可以看到Counter正在发生变化,但没有更新我的UI,我这是怎么尝试使用我的UITextBlock更新:

<TextBlock Name="tbStatusBar" Text="{Binding Source={x:Static my:Machine.Counter}}" /> 

所以我的问题是我做错了什么?

+1

您应该在AddMachine中用'Counter ++'替换'_counter ++'。 – Clemens

+0

我已经试过了,这不是问题 – user979033

+0

你实际使用WPF 4.5吗? StaticPropertyChanged事件机制不适用于较旧的版本。 – Clemens

回答

0

首先,您必须确保使用WPF 4.5,因为StaticPropertyChanged事件机制不适用于旧版本。

然后,在AddMachine,你应该更新属性,而不是它支持字段:

public void AddMachine(Machine machine) 
{ 
    Counter++; 
} 

最后,你必须从静态源绑定表达式更改为一个静态属性的路径(注意括号):

<TextBlock Text="{Binding Path=(my:Machine.Counter)}" /> 
+0

现在确定这是工作,但我有另一个,我的静态变量我访问从不同的线程,所以每次我更新这个领域我这样做:Interlocked.Increment(ref _counter);所以现在这甚至没有用Counter而不是_counter编译,所以我把它改成Counter ++,并且在这个字段的定义中增加了volatile,现在可以吗? – user979033

+0

不知道。我想这是另一个问题。 – Clemens