WPF 控件库Live Charts 折线图平移及缩放功能

此博客展示了如何使用LiveCharts库在WPF应用中实现图表的缩放和平移功能。通过ZoomingOptions属性,可以设置鼠标滚轮缩放和点击拖动平移的操作模式,包括None、X、Y和XY四种模式。同时,提供了代码示例展示后台逻辑和UI界面的实现方式,包括数据生成、图表系列设置、坐标轴格式化以及重置缩放的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述

功能效果如上图所示 

使用Chart.Zoom(默认为None)和Chart.Pan(默认为Unset),使用鼠标滚轮放大/缩小,单击,按住并拖动以进行平移。
后台代码

using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
using LiveCharts;
using LiveCharts.Defaults;
using LiveCharts.Wpf;
 
namespace Wpf.CartesianChart.ZoomingAndPanning
{
    /// <summary>
    /// Interaction logic for ZoomingAndPanning.xaml
    /// </summary>
    public partial class ZoomingAndPanning : INotifyPropertyChanged
    {
        private ZoomingOptions _zoomingMode;
 
        public ZoomingAndPanning()
        {
            InitializeComponent();
 
            var gradientBrush = new LinearGradientBrush {StartPoint = new Point(0, 0),
                EndPoint = new Point(0, 1)};
            gradientBrush.GradientStops.Add(new GradientStop(Color.FromRgb(33, 148, 241), 0));
            gradientBrush.GradientStops.Add(new GradientStop(Colors.Transparent, 1));
 
            SeriesCollection = new SeriesCollection
            {
                new LineSeries
                {
                    Values = GetData(),
                    Fill = gradientBrush,
                    StrokeThickness = 1,
                    PointGeometrySize = 0
                }
            };
 
            ZoomingMode = ZoomingOptions.X;
 
            XFormatter = val => new DateTime((long) val).ToString("dd MMM");
            YFormatter = val => val.ToString("C");
 
            DataContext = this;
        }
 
        public SeriesCollection SeriesCollection { get; set; }
        public Func<double, string> XFormatter { get; set; }
        public Func<double, string> YFormatter { get; set; }
 
        public ZoomingOptions ZoomingMode
        {
            get { return _zoomingMode; }
            set
            {
                _zoomingMode = value;
                OnPropertyChanged();
            }
        }
 
        private void ToogleZoomingMode(object sender, RoutedEventArgs e)
        {
            switch (ZoomingMode)
            {
                case ZoomingOptions.None:
                    ZoomingMode = ZoomingOptions.X;
                    break;
                case ZoomingOptions.X:
                    ZoomingMode = ZoomingOptions.Y;
                    break;
                case ZoomingOptions.Y:
                    ZoomingMode = ZoomingOptions.Xy;
                    break;
                case ZoomingOptions.Xy:
                    ZoomingMode = ZoomingOptions.None;
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
 
        private ChartValues<DateTimePoint> GetData()
        {
            var r = new Random();
            var trend = 100;
            var values = new ChartValues<DateTimePoint>();
 
            for (var i = 0; i < 100; i++)
            {
                var seed = r.NextDouble();
                if (seed > .8) trend += seed > .9 ? 50 : -50;
                values.Add(new DateTimePoint(DateTime.Now.AddDays(i), trend + r.Next(0, 10)));
            }
 
            return values;
        }
 
        public event PropertyChangedEventHandler PropertyChanged;
 
        protected virtual void OnPropertyChanged(string propertyName = null)
        {
            if (PropertyChanged != null) PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
 
        private void ResetZoomOnClick(object sender, RoutedEventArgs e)
        {
            //Use the axis MinValue/MaxValue properties to specify the values to display.
            //use double.Nan to clear it.
 
            X.MinValue = double.NaN;
            X.MaxValue = double.NaN;
            Y.MinValue = double.NaN;
            Y.MaxValue = double.NaN;
        }
    }
 
    public class ZoomingModeCoverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            switch ((ZoomingOptions) value)
            {
                case ZoomingOptions.None:
                    return "None";
                case ZoomingOptions.X:
                    return "X";
                case ZoomingOptions.Y:
                    return "Y";
                case ZoomingOptions.Xy:
                    return "XY";
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
 
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

 UI界面

<UserControl x:Class="Wpf.CartesianChart.ZoomingAndPanning.ZoomingAndPanning"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:Wpf.CartesianChart"
             xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
             xmlns:zoomingAndPanning="clr-namespace:Wpf.CartesianChart.ZoomingAndPanning"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300" d:DataContext="{d:DesignInstance local:ZoomingAndPanning}">
    <UserControl.Resources>
        <zoomingAndPanning:ZoomingModeCoverter x:Key="ZoomingModeCoverter"></zoomingAndPanning:ZoomingModeCoverter>
    </UserControl.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        <TextBlock Grid.Row="0" TextWrapping="Wrap">
            Use the Chart.Zoom property to enable zooming and panning, you have some options: None, X, Y and XY, click, hold and drag the chart for panning.
        </TextBlock>
        <StackPanel Grid.Row="1">
            <Button Click="ToogleZoomingMode">
                <TextBlock>Toggle zoming mode, current is: 
                    <TextBlock Text="{Binding ZoomingMode, Converter={StaticResource ZoomingModeCoverter}}"/>
                </TextBlock>
            </Button>
            <Button Click="ResetZoomOnClick">Reset Zoom</Button>
        </StackPanel>
        <lvc:CartesianChart Grid.Row="2" Series="{Binding SeriesCollection}" Zoom="{Binding ZoomingMode}" >
            <lvc:CartesianChart.AxisX>
                <lvc:Axis Name="X" LabelFormatter="{Binding XFormatter}" 
                          Separator="{x:Static lvc:DefaultAxes.CleanSeparator}"/>
            </lvc:CartesianChart.AxisX>
            <lvc:CartesianChart.AxisY>
                <lvc:Axis Name="Y" LabelFormatter="{Binding YFormatter}"/>
            </lvc:CartesianChart.AxisY>
        </lvc:CartesianChart>
    </Grid>
</UserControl>

之前两此发的库http://download.youkuaiyun.com/detail/maiker/9621027可以作废,本次为最新的,其中测试了历史曲线的动态显示,这是对Microsoft WpfToolkit的更新和扩展: 1、将库版本升级到.NET 4.5,对命名控件进行了替换处理 2、实现了单数据Chart图的混合颜色显示,可通过修改资源字典调整和添加颜色 3、可控制柱状图的数值显示 4、坐标轴文本可倾斜显示 5、添加了StepLine图和圆环图,圆环半径比例系数可设定 6、Legend可位于右侧和底部,以及是否显示, 可控制Chart Title是否显示 7、柱状图缝隙间隔可调整 8、全方面的加入了各种加载动画效果,动画效果可屏蔽,同时原系统自带动画效果,可叠加,这是两种不同的效果,可以互补性的单个使用 9、设计了四种主题颜色,各人可以针对图形颜色和背景色进行更好的搭配,在用户项目中,可以自己添加新的主题,在程序中更换主题的操作中,与资源集合字典相关的颜色需要重新加载图形才能更新(用户也可以把这部分资源从主题中删除,主要就是Chart的两个资源字典集合的属性设定),但在应用程序级别中指向主题资源时,则不存在任何问题。 10、扩展了时间轴的应用,在新的DateTimeChart中可以通过鼠标平移缩放时间轴,并测试了一个例子用于动态显示历史曲线 总而言之,微软的控件库做得很标准,还是很好修改的。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值