【问题标题】:Is there a way to create cpu perfmon dashboard using WPF .net?有没有办法使用 WPF .net 创建 cpu perfmon 仪表板?
【发布时间】:2020-12-11 02:49:03
【问题描述】:

我使用 winforms 创建了它,只添加了 permon 类并下载了一些实时仪表板,但我发现在 WPF 中相当困难

【问题讨论】:

  • 好吧,你必须了解 WPF。但是是的,这是可能的,而且结果可能会比在 Winforms 中更好。
  • 真正学习 wpf 需要时间......但它可以很有趣。只能坚持下去。
  • 或至少任何提示,我如何在 WPF 中使用 winforms 控件?所以我将使用工具箱中的 perfmoncounter

标签: c# wpf windows visual-studio performance


【解决方案1】:

a lot of tools 允许在 WPF 中绘制各种图形。

但由于我没有找到任何手动图形绘制实现,我创建了示例 - 如何使用 MVVM 编程模式在 WPF 中绘制图形。

0。辅助类

为了正确和简单的 MVVM 实现,我将使用以下 2 个类。

NotifyPropertyChanged.cs - 通知 UI 更改。

public class NotifyPropertyChanged : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

RelayCommand.cs - 便于使用命令(Button

public class RelayCommand : ICommand
{
    private readonly Action<object> _execute;
    private readonly Predicate<object> _canExecute;

    public event EventHandler CanExecuteChanged
    {
        add => CommandManager.RequerySuggested += value;
        remove => CommandManager.RequerySuggested -= value;
    }

    public RelayCommand(Action<object> execute, Predicate<object> canExecute = null)
        => (_execute, _canExecute) = (execute, canExecute);

    public bool CanExecute(object parameter)
        => _canExecute == null || _canExecute(parameter);

    public void Execute(object parameter)
        => _execute(parameter);
}

1。数据实现

由于图表由不断转动的点组成,因此我实现了只有一种方法 Push() 的循环集合。

RoundRobinCollection.cs

public class RoundRobinCollection : NotifyPropertyChanged
{
    private readonly List<float> _values;
    public IReadOnlyList<float> Values => _values;

    public RoundRobinCollection(int amount)
    {
        _values = new List<float>();
        for (int i = 0; i < amount; i++)
            _values.Add(0F);
    }

    public void Push(float value)
    {
        _values.RemoveAt(0);
        _values.Add(value);
        OnPropertyChanged(nameof(Values));
    }
}

2。值集合到多边形点转换器

用于视图标记

PolygonConverter.cs

public class PolygonConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        PointCollection points = new PointCollection();
        if (values.Length == 3 && values[0] is IReadOnlyList<float> dataPoints && values[1] is double width && values[2] is double height)
        {
            points.Add(new Point(0, height));
            points.Add(new Point(width, height));
            double step = width / (dataPoints.Count - 1);
            double position = width;
            for (int i = dataPoints.Count - 1; i >= 0; i--)
            {
                points.Add(new Point(position, height - height * dataPoints[i] / 100));
                position -= step;
            }
        }
        return points;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) => null;
}

3。查看模型

包含App所有业务逻辑的主类

public class MainViewModel : NotifyPropertyChanged
{
    private bool _graphEnabled;
    private float _lastCpuValue;
    private ICommand _enableCommand;

    public RoundRobinCollection ProcessorTime { get; }

    public string ButtonText => GraphEnabled ? "Stop" : "Start";

    public bool GraphEnabled
    {
        get => _graphEnabled;
        set
        {
            if (value != _graphEnabled)
            {
                _graphEnabled = value;
                OnPropertyChanged();
                OnPropertyChanged(nameof(ButtonText));
                if (value)
                    ReadCpu();
            }
        }
    }

    public float LastCpuValue
    {
        get => _lastCpuValue;
        set
        {
            _lastCpuValue = value;
            OnPropertyChanged();
        }
    }

    public ICommand EnableCommand => _enableCommand ?? (_enableCommand = new RelayCommand(parameter =>
    {
        GraphEnabled = !GraphEnabled;
    }));

    private async void ReadCpu()
    {
        try
        {
            using (PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"))
            {
                while (GraphEnabled)
                {
                    LastCpuValue = cpuCounter.NextValue();
                    ProcessorTime.Push(LastCpuValue);
                    await Task.Delay(1000);
                }
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }
    }

    public MainViewModel()
    {
        ProcessorTime = new RoundRobinCollection(100);
    }
}

声明: 不推荐使用async void 来制作async,但在这里使用是安全的,因为任何可能的Exception 都将在内部处理。有关为什么 async void 不好的更多信息,请参阅文档 - Asynchronous Programming

4。查看

应用的整个 UI 标记

<Window x:Class="CpuUsageExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:CpuUsageExample"
        mc:Ignorable="d"
        Title="MainWindow" Height="400" Width="800" >
    <Window.DataContext>
        <local:MainViewModel/><!-- attach View Model -->
    </Window.DataContext>
    <Window.Resources>
        <local:PolygonConverter x:Key="PolygonConverter"/><!-- attach Converter -->
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <WrapPanel>
            <Button Margin="5" Padding="10,0" Content="{Binding ButtonText}" Command="{Binding EnableCommand}"/>
            <TextBlock Margin="5" Text="CPU:"/>
            <TextBlock Margin="0, 5" Text="{Binding LastCpuValue, StringFormat=##0.##}" FontWeight="Bold"/>
            <TextBlock Margin="0, 5" Text="%" FontWeight="Bold"/>
        </WrapPanel>
        <Border Margin="5" Grid.Row="1" BorderThickness="1" BorderBrush="Gray" SnapsToDevicePixels="True">
            <Canvas ClipToBounds="True">
                <Polygon Stroke="CadetBlue" Fill="AliceBlue">
                    <Polygon.Resources>
                        <Style TargetType="Polygon">
                            <Setter Property="Points">
                                <Setter.Value>
                                    <MultiBinding Converter="{StaticResource PolygonConverter}">
                                        <Binding Path="ProcessorTime.Values"/>
                                        <Binding Path="ActualWidth" RelativeSource="{RelativeSource AncestorType=Canvas}"/>
                                        <Binding Path="ActualHeight" RelativeSource="{RelativeSource AncestorType=Canvas}"/>
                                    </MultiBinding>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </Polygon.Resources>
                </Polygon>
            </Canvas>
        </Border>
    </Grid>
</Window>

P.S.没有代码隐藏

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
}

【讨论】:

  • 这是一个很大的帮助,非常感谢你:-)
  • 我正在尝试在此图中添加 x(CPU)和 y(至少 3-4 个间隔的日期)坐标但是没有运气!!!
  • @user8758891 您可以在底层 Canvas 上绘制网格 (example)
  • @user8758891 添加文本并非易事,因为您可能需要修改 RRC 以存储每个值的时间戳。然后在Canvas 下添加一些ItemsControl 并通过另一个转换器将其绑定到同一个RRC,或者创建一些额外的ObservableCollection 将包含每个TextBlock 的坐标和里面的文本。然后一次性修改这两个集合。
  • 谢谢我已经接受了,这对我有帮助,再次感谢
猜你喜欢
  • 2018-10-22
  • 2021-04-17
  • 2017-03-04
  • 2022-10-25
  • 1970-01-01
  • 2020-02-06
  • 2022-12-22
  • 2019-11-11
  • 2021-09-27
相关资源
最近更新 更多