如何使标签显示cpu加载实时数据

时间:2015-11-30 01:28:42

标签: c# wpf label cpu

我知道如何使用性能计数器获取cpu加载值,但不知道如何使标签实时显示

1 个答案:

答案 0 :(得分:0)

将您的标签内容绑定到ViewModel:

XAML(YourView.xaml.cs):

<Label Content="{Binding CPUText}" />

您的视图模型如下所示:

public class YourViewModel : INotifyPropertyChanged
{

  public void GetCpuText()
  {
     //your code here.... 
     //it would populate your CPUText property...

     CPUText = .... (your code to get the cpu info)
  }
  private _cpuText;

  public string CPUText
  {
     get
     {
        return _cpuText;
     }
     set
     {
        _cpuText = value;

         NotifyPropertyChanged("CPUText");
     }
  }

  public event PropertyChangedEventHandler PropertyChanged;

  protected void NotifyPropertyChanged(String info) {
    if (PropertyChanged != null) {
        PropertyChanged(this, new PropertyChangedEventArgs(info));
    }
  }
}

使这项工作的一个示例是创建视图,将该视图的DataContext设置为ViewModel类:

var view = new YourView();
view.DataContext = new YourViewModel();
view.GetCpuText();