翼度科技»论坛 编程开发 .net 查看内容

WPF中轻松生成动态图表:实例详解(MVVM模式)

5

主题

5

帖子

15

积分

新手上路

Rank: 1

积分
15
 
概述:本文代码示例演示了如何在WPF中使用LiveCharts库创建动态条形图。通过创建数据模型、ViewModel和在XAML中使用`CartesianChart`控件,你可以轻松实现图表的数据绑定和动态更新。我将通过清晰的步骤指南包括详细的中文注释,帮助你快速理解并应用这一功能。
先上效果:
 
在WPF中使用LiveCharts生成动态的条形图表需要以下步骤。以下是详细的实例源代码:
步骤 1: 引用LiveCharts库

首先,在项目中引用LiveCharts库。你可以通过NuGet包管理器来安装LiveCharts.Wpf:
  1. Install-Package LiveCharts.Wpf
复制代码
步骤 2: 创建WPF项目

创建一个新的WPF项目,确保已经在XAML文件中引用了LiveCharts的命名空间:
  1. xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
复制代码
步骤 3: 创建数据模型

创建一个数据模型,用于存储条形图的数据:
  1. // BarChartData.cs
  2. public class BarChartData
  3. {
  4.     public string Category { get; set; }
  5.     public double Value { get; set; }
  6. }
复制代码
步骤 4: 创建ViewModel

创建一个ViewModel类,用于处理图表的数据和逻辑。在这个类中,你将生成数据并将其绑定到图表控件:
  1. public partial class ViewModel : ViewModelBase
  2. {
  3.     private readonly Random _r = new();
  4.     private static readonly (string, double)[] s_initialData =
  5.     {
  6.         ("上海", 500),
  7.         ("北京", 450),
  8.         ("深圳", 520),
  9.         ("广州", 550),
  10.         ("重庆", 660),
  11.         ("天津", 920),
  12.         ("成都", 1000)
  13.     };
  14.     [ObservableProperty]
  15.     private ISeries[] _series =
  16.         s_initialData
  17.             .Select(x => new RowSeries<ObservableValue>
  18.             {
  19.                 Values = new[] { new ObservableValue(x.Item2) },
  20.                 Name = x.Item1,
  21.                 Stroke = null,
  22.                 MaxBarWidth = 25,
  23.                 DataLabelsPaint = new SolidColorPaint(new SKColor(245, 245, 245)),
  24.                 DataLabelsPosition = DataLabelsPosition.End,
  25.                 DataLabelsTranslate = new LvcPoint(-1, 0),
  26.                 DataLabelsFormatter = point => $"{point.Context.Series.Name} {point.PrimaryValue}"
  27.             })
  28.             .OrderByDescending(x => ((ObservableValue[])x.Values!)[0].Value)
  29.             .ToArray();
  30.     [ObservableProperty]
  31.     private Axis[] _xAxes = { new Axis { SeparatorsPaint = new SolidColorPaint(new SKColor(220, 220, 220)) } };
  32.     [ObservableProperty]
  33.     private Axis[] _yAxes = { new Axis { IsVisible = false } };
  34.     /// <summary>
  35.     /// 动态修改数据,实际项目中读取真实数据
  36.     /// </summary>
  37.     public void RandomIncrement()
  38.     {
  39.         foreach (var item in Series)
  40.         {
  41.             if (item.Values is null) continue;
  42.             var i = ((ObservableValue[])item.Values)[0];
  43.             i.Value += _r.Next(0, 100);
  44.         }
  45.         //对新数据重新排序
  46.         Series = Series.OrderByDescending(x => ((ObservableValue[])x.Values!)[0].Value).ToArray();
  47.     }
  48. }
复制代码
步骤 5: 在XAML中使用图表控件

在XAML中使用LiveCharts的 CartesianChart 控件来显示条形图:
  1. <Window x:
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  5.         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  6.         xmlns:lvc="clr-namespace:LiveChartsCore.SkiaSharpView.WPF;assembly=LiveChartsCore.SkiaSharpView.WPF"
  7.         xmlns:local="clr-namespace:Sample_Charts_Bars"
  8.         mc:Ignorable="d"
  9.         Title="MainWindow" Height="450" Width="800">
  10.     <Window.DataContext>
  11.         <local:ViewModel/>
  12.     </Window.DataContext>
  13.     <Grid>
  14.         <Grid.RowDefinitions>
  15.             <RowDefinition Height="*"/>
  16.         </Grid.RowDefinitions>
  17.         <lvc:CartesianChart Title="{Binding Title}"
  18.             Series="{Binding Series}"
  19.             XAxes="{Binding XAxes}"
  20.             YAxes="{Binding YAxes}"
  21.             TooltipPosition="Hidden">
  22.         </lvc:CartesianChart>
  23.     </Grid>
  24. </Window>
复制代码
步骤 6: 在MainWindow中设置DataContext

在MainWindow.xaml.cs中设置ViewModel的DataContext,以便数据绑定:
  1. // MainWindow.xaml.cs
  2. using System.Windows;
  3. namespace YourNamespace
  4. {
  5.     public partial class MainWindow : Window
  6.     {
  7.         public MainWindow()
  8.         {
  9.             InitializeComponent();
  10.             Update();
  11.         }
  12.         public async void Update()
  13.         {
  14.             var vm = (ViewModel)DataContext;
  15.             while (true)
  16.             {
  17.                 //更新数据
  18.                 Application.Current.Dispatcher.Invoke(vm.RandomIncrement);
  19.                 await Task.Delay(100);
  20.             }
  21.         }
  22.     }
  23. }
复制代码
需要查看更多实例请关注我,后面将逐个发布。

源代码获取:https://pan.baidu.com/s/1EtHg5dvB7ZEQDI9Y3VICpw?pwd=6666
 



来源:https://www.cnblogs.com/hanbing81868164/p/18164891
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具