WPF仿LiveCharts实现饼图的绘制

 更新时间:2022年07月29日 09:34:23   作者:驚鏵  
这篇文章主要介绍了如何利用WPF仿LiveCharts实现饼图的绘制,文中的示例代码讲解详细,对我们学习或工作有一定帮助,需要的可以参考一下

每日一笑

下班和实习生一起回家,公交站等车,一乞丐把碗推向实习生乞讨。这时,实习生不慌不忙的说了句:“我不要你的钱,你这钱来的也不容易。” 

前言 

有小伙伴需要统计图。

效果预览(更多效果请下载源码体验)

一、PieControl.cs

using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using WpfPieControl.Models;

namespace WpfPieControl
{
    public class PieControl: Control
    {
        public ObservableCollection<PieSegmentModel> PieSegmentModels
        {
            get { return (ObservableCollection<PieSegmentModel>)GetValue(PieSegmentModelsProperty); }
            set { SetValue(PieSegmentModelsProperty, value); }
        }

        public static readonly DependencyProperty PieSegmentModelsProperty =
            DependencyProperty.Register("PieSegmentModels", typeof(ObservableCollection<PieSegmentModel>), typeof(PieControl), new UIPropertyMetadata(OnPieSegmentModelChanged));

        private static void OnPieSegmentModelChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            PieControl pieControl = d as PieControl;
            if (e.NewValue != null)
            {
                var array = e.NewValue as ObservableCollection<PieSegmentModel>;
                double angleNum = 0;
                foreach (var item in array)
                {
                    var color = new SolidColorBrush((Color)ColorConverter.ConvertFromString(pieControl.ColorArray[array.IndexOf(item)]));
                    item.Color = color;
                    item.StartAngle = angleNum;
                    item.EndAngle = angleNum + item.Value / 100 * 360;
                    angleNum = item.EndAngle;
                }
            }
        }
        /// <summary>
        /// colors
        /// </summary>
        private string[] ColorArray = new string[] { "#FDC006", "#607E89", "#2095F2", "#F34336" };


        /// <summary>
        /// 0~1
        /// </summary>
        public double ArcThickness
        {
            get { return (double)GetValue(ArcThicknessProperty); }
            set { SetValue(ArcThicknessProperty, value); }
        }

        public static readonly DependencyProperty ArcThicknessProperty =
            DependencyProperty.Register("ArcThickness", typeof(double), typeof(PieControl), new PropertyMetadata(1.0));


        static PieControl()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(PieControl), new FrameworkPropertyMetadata(typeof(PieControl)));
        }
    }
}

二、App.xaml

<Style TargetType="{x:Type local:PieControl}">
            <Setter Property="UseLayoutRounding" Value="True" />
            <!--<Setter Property="Background" Value="#252525"/>-->
            <Setter Property="Foreground" Value="White"/>
            <Setter Property="Width" Value="250"/>
            <Setter Property="Height" Value="250"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type local:PieControl}">
                        <ItemsControl Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" 
                                      ItemsSource="{TemplateBinding PieSegmentModels}"
                                      Background="{TemplateBinding Background}">
                            <ItemsControl.ItemsPanel>
                                <ItemsPanelTemplate>
                                    <Grid IsItemsHost="True"/>
                                </ItemsPanelTemplate>
                            </ItemsControl.ItemsPanel>
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <ed:Arc Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"
                                                ArcThickness="{Binding ArcThickness,RelativeSource={RelativeSource FindAncestor,AncestorType=local:PieControl}}" ArcThicknessUnit="Percent"
                                                EndAngle="{Binding EndAngle}"
                                                StartAngle="{Binding StartAngle}"
                                                Stretch="None"
                                                ToolTip="{Binding Name}"
                                                Stroke="{Binding ColorStroke}"
                                                StrokeThickness="2"
                                                Fill="{Binding Color}">
                                    </ed:Arc>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
</Style>

三、MainWindow.xaml

<Window x:Class="WpfPieControl.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:WpfPieControl"
        mc:Ignorable="d"
        Title="微信公众号:WPF开发者" Height="450" Width="800">
    <StackPanel>
        <WrapPanel Margin="10">
            <local:PieControl PieSegmentModels="{Binding PieSegmentModels,RelativeSource={RelativeSource AncestorType=local:MainWindow}}" ArcThickness="1"/>
            <local:PieControl PieSegmentModels="{Binding PieSegmentModels,RelativeSource={RelativeSource AncestorType=local:MainWindow}}" 
                                  Margin="4,0"
                                  ArcThickness="{Binding ElementName=PRAT_Slider,Path=Value}"/>
            <local:PieControl PieSegmentModels="{Binding PieSegmentModels,RelativeSource={RelativeSource AncestorType=local:MainWindow}}" ArcThickness="0.65"/>
        </WrapPanel>
        <Slider Maximum="0.9" Minimum="0.1" x:Name="PRAT_Slider" Margin="10" Width="200"/>
        <Button Content="更新" Click="Button_Click" VerticalAlignment="Bottom" Width="200"/>
    </StackPanel>
</Window>

四、MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WpfPieControl.Models;

namespace WpfPieControl
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public ObservableCollection<PieSegmentModel> PieSegmentModels
        {
            get { return (ObservableCollection<PieSegmentModel>)GetValue(PieSegmentModelsProperty); }
            set { SetValue(PieSegmentModelsProperty, value); }
        }

        public static readonly DependencyProperty PieSegmentModelsProperty =
            DependencyProperty.Register("PieSegmentModels", typeof(ObservableCollection<PieSegmentModel>), typeof(MainWindow), new PropertyMetadata(null));

        List<ObservableCollection<PieSegmentModel>> collectionList = new List<ObservableCollection<PieSegmentModel>>();
        public MainWindow()
        {
            InitializeComponent();

            PieSegmentModels = new ObservableCollection<PieSegmentModel>();
            var collection1 = new ObservableCollection<PieSegmentModel>();
            collection1.Add(new PieSegmentModel { Name = "一", Value = 10 });
            collection1.Add(new PieSegmentModel { Name = "二", Value = 20 });
            collection1.Add(new PieSegmentModel { Name = "三", Value = 25 });
            collection1.Add(new PieSegmentModel { Name = "四", Value = 45 });
            var collection2 = new ObservableCollection<PieSegmentModel>();
            collection2.Add(new PieSegmentModel { Name = "一", Value = 30 });
            collection2.Add(new PieSegmentModel { Name = "二", Value = 15 });
            collection2.Add(new PieSegmentModel { Name = "三", Value = 10 });
            collection2.Add(new PieSegmentModel { Name = "四", Value = 55 });
            collectionList.AddRange(new[] { collection1, collection2 });

            PieSegmentModels = collectionList[0];
        }
        bool isRefresh = false;
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (!isRefresh)
                PieSegmentModels = collectionList[1];
            else
                PieSegmentModels = collectionList[0];
            isRefresh = !isRefresh;

        }
    }
}

到此这篇关于WPF仿LiveCharts实现饼图的绘制的文章就介绍到这了,更多相关WPF饼图内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • C#验证控件validator的简单使用

    C#验证控件validator的简单使用

    这篇文章主要介绍了C#验证控件validator的简单使用方法和示例,十分的简单实用,有需要的小伙伴可以参考下。
    2015-06-06
  • C#语言async await之迭代器工作原理示例解析

    C#语言async await之迭代器工作原理示例解析

    这篇文章主要为大家介绍了C#语言async await之迭代器工作原理示例解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-05-05
  • C#安装OpenCvSharp4的实现步骤

    C#安装OpenCvSharp4的实现步骤

    OpenCv是一款开源的图像处理库,本文就介绍了C#安装OpenCvSharp4的实现步骤,具有一定的参考价值,感兴趣的可以了解一下
    2022-05-05
  • C# 基础入门--注释

    C# 基础入门--注释

    本文主要介绍了C#中注释的相关知识,具有很好的参考价值,下面跟着小编一起来看下吧
    2017-03-03
  • WinForm判断关闭事件来源于用户点击右上角“关闭”按钮的方法

    WinForm判断关闭事件来源于用户点击右上角“关闭”按钮的方法

    这篇文章主要介绍了WinForm判断关闭事件来源于用户点击右上角“关闭”按钮的方法,涉及C#针对WinForm事件的判定技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-09-09
  • vs2022程序打包文档教程图文详解

    vs2022程序打包文档教程图文详解

    这篇文章主要介绍了vs2022程序打包文档教程,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-10-10
  • C# 实现微信自定义分享的示例代码

    C# 实现微信自定义分享的示例代码

    这篇文章主要介绍了C# 实现微信自定义分享的示例代码,文中通过代码示例给大家介绍的非常详细,对大家的学习或工作有一定的帮助,感兴趣的同学可以自己动手尝试一下
    2024-02-02
  • DevExpress GridView自动滚动效果

    DevExpress GridView自动滚动效果

    这篇文章主要为大家详细介绍了DevExpress GridView自动滚动效果,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-06-06
  • C# 模式匹配完全指南

    C# 模式匹配完全指南

    模式匹配是一种高端的使用机制,它允许程序员在开发的时候以对象的类型作为条件筛选和分情况处理的一种手段,本文给大家介绍C# 模式匹配完全指南,感兴趣的朋友跟随小编一起看看吧
    2022-03-03
  • C#实现老板键功能的代码

    C#实现老板键功能的代码

    最近在做项目中遇到需要增加个老板键功能,找一惯的方式,开始从网络下手寻找: 关键字类似”C# 老板键“,一搜,一堆又一堆,然而出来的代码大多数都不是太合适,下面给大家分享下自己的解决方案已经一个网友的解决方案,有需要的小伙伴可以参考下。
    2015-05-05

最新评论