Click here to Skip to main content
15,860,943 members
Articles / Desktop Programming / WPF
Tip/Trick

WPF Bar Chart as simple as possible

Rate me:
Please Sign up or sign in to vote.
4.82/5 (10 votes)
27 May 2014CPOL2 min read 46K   3.5K   23   14
Creating a bar chart with most of needed features.

Image 1

Introduction

Most of User controls in WPF are heavy to load, specially when we use them inside another control(e.g. DataGrid). If we use a DataGrid, Chart or another control inside the rows details in DataGrid, it makes our form's loading too slow. Because of that,I decided to create a light weight BarChart control to decrease this problem.

In this control we can bind items and legends to it's ItemsSource property. There are 3 properties to introducing horizontal, vertical and legends properties in Item source to chart, : HorizontalPropertyName, VerticalPropertyName and LegendPropertyName.

In additional of this, we can change some appearance parameters such as changing visibility of Values labels and Legends list, and manipulating legends header and color.

Using the code

In control's class, Draw() method creates our view by using our ItemsSource or Items properties. In some events we call this method to refresh our view. This method creates a Border control per each information, then locates that on a canvas by calculating its location. For calculating our drawing area and borders, we use count of legends and horizontal values. Borders width dynamically changes by control width and count of legends.

Our second main method is GetLegends(). By using this method we can fetch all of legends by there property name declared in LegendPropertyName property.

C#
private void GetLegends()
{
    if (Legends == null)
        Legends = new ObservableCollection<Legend>();
 
    if (Items == null)
        return;
 
    Random rand = new Random(DateTime.Now.Millisecond);
    foreach (var item in Items)
    {
        var LegValue = item.GetType().GetProperty(LegendPropertyName).GetValue(item, null);
 
        var leg = from Legend lc in Legends where lc.LegendType.Equals(LegValue) select lc;
        if (leg.Count() == 0)
        {
             Legend legend = new Legend();
             legend.LegendType = LegValue;
             Color c = Color.FromRgb(Convert.ToByte(rand.Next(256)), Convert.ToByte(rand.Next(256)), Convert.ToByte(rand.Next(256)));
             legend.Color = new SolidColorBrush(c);
             legend.IsVisibleChanged += (s, e) =>
                    {
                        Draw(false);
                    };
 
             Legends.Add(legend);
        }
        else
        leg.First().IsVisibleChanged += (s, e) =>
        {
             Draw(false);
        };
    }
} 


For declaring legends and changing there property, I defined a class with name Legend that inherits from DependencyObject and INotifyPropertyChanged. We have some properties(LegendType, DisplayName, Color and IsVisible) and one event(IsVisibleChanged) in this class.

C#
public class Legend : DependencyObject, INotifyPropertyChanged
    {
        #region Constructors
        public Legend()
        {
        }
        #endregion Constructors
 
        #region Properties
        private object _legend = null;
        public object LegendType
        {
            get { return _legend; }
            set
            {
                _legend = value;
                Notify("Legend");
            }
        }
 
        private string _displayName = String.Empty;
        public string DisplayName
        {
            get
            {
                if (String.IsNullOrEmpty(_displayName))
                    if (LegendType == null)
                        return String.Empty;
                    else
                        return LegendType.ToString();
                else
                    return _displayName;
            }
            set
            {
                _displayName = value;
                Notify("DisplayName");
            }
        }
 
        private Brush _color = null;
        public Brush Color
        {
            get { return _color; }
            set
            {
                _color = value;
                Notify("Color");
            }
        }
 
        private bool _isVisible = true;
        public bool IsVisible
        {
            get { return _isVisible; }
            set
            {
                if (_isVisible != value)
                {
                    _isVisible = value;
                    Notify("IsVisible");
                    if (IsVisibleChanged != null)
                        IsVisibleChanged(this, new RoutedEventArgs());
                }
            }
        }
        #endregion Properties
 
        #region Events
        public event RoutedEventHandler IsVisibleChanged;
        #endregion Events
 
        #region Methods
        public event PropertyChangedEventHandler PropertyChanged;
        private void Notify(string property)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
        #endregion Methods
    } 

For using this control we can declare a class or structure for passing main properties to it and use them to draw bars. For example, I declared a simple class to do this.

C#
public class MyData
   {
       public MyData()
       {
       }

       public int Year { get; set; }

       public double Value { get; set; }

       public WorkTypes WorkType { get; set; }
   }

And an Enum to indicate my legends.

C#
public enum WorkTypes
   {
       Buy,
       Sell,
       Receipt,
       Draft
   }

By using a List, ArrayList, ObservableCollection or other classes inherited from IEnumerable, we can create an array of our class and pass that to controls Items property or bind that to ItemsSource property.

XML
<controls:BarChart x:Name="BarChart1"
                   LegendPropertyName="WorkType"
                   VerticalPropertyName="Value"
                   HorizontalPropertyName="Year"
                   FontFamily="Tahoma"
                   ItemsSource="{Binding Path=Data,
                                 RelativeSource={RelativeSource AncestorType=Window}}">

In above code, I passed "WorkType" to LegendPropertyName, "Value" to VerticalPropertyName and Year to HorizontalPropertyName to use this names for accessing value of this properties in my class. For presenting my information in chart, I binded Data property in my class to ItemsSource property of control.

For customizing legends, User can change their attributes and properties. Some thing like this :

XML
<controls:BarChart.Legends>
     <controls:Legend DisplayName="Buy" LegendType="{x:Static my:WorkTypes.Buy}">
          <controls:Legend.Color>
               <LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
                     <GradientStop Color="#FF5C8EFF" Offset="0" />
                     <GradientStop Color="#FFC2C2FC" Offset="1" />
               </LinearGradientBrush>
          </controls:Legend.Color>
     </controls:Legend>
     <controls:Legend DisplayName="Sell" LegendType="{x:Static my:WorkTypes.Sell}">
          <controls:Legend.Color>
               <LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
                    <GradientStop Color="#FF63B700" Offset="0" />
                    <GradientStop Color="#FFBDEB94" Offset="1" />
               </LinearGradientBrush>
          </controls:Legend.Color>
     </controls:Legend>
     <controls:Legend DisplayName="Receipt" LegendType="{x:Static my:WorkTypes.Receipt}">
          <controls:Legend.Color>
               <LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
                     <GradientStop Color="#FFA9B700" Offset="0" />
                     <GradientStop Color="#FFEBEB94" Offset="1" />
               </LinearGradientBrush>
          </controls:Legend.Color>
     </controls:Legend>
     <controls:Legend DisplayName="Draft" LegendType="{x:Static my:WorkTypes.Draft}">
          <controls:Legend.Color>
               <LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
                      <GradientStop Color="#FFB700B7" Offset="0" />
                      <GradientStop Color="#FFD794EB" Offset="1" />
               </LinearGradientBrush>
          </controls:Legend.Color>
     </controls:Legend>
</controls:BarChart.Legends>

Points of Interest

In this control, I used dynamic property names for my first time. With dynamic property names, we can improve control's flexibility and use controls in every forms and projects without needing any [large] changes.

Finally

I hope this code and this user control help you to creating new controls.

I apologies for my poor description because of my weak English knowledge.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Keyhan Iranian
Iran (Islamic Republic of) Iran (Islamic Republic of)
I'm addict of developing softwares and designing solutions for projects.
My favorite work in programming is designing Components and user controls.

Comments and Discussions

 
PraiseFantastic Control! Pin
Jqkunz24-Mar-21 7:14
Jqkunz24-Mar-21 7:14 
Bugnice post but there is a bug...... Pin
Member 1257355723-Sep-16 23:51
Member 1257355723-Sep-16 23:51 
GeneralRe: nice post but there is a bug...... Pin
Amin Esmaeily9-Oct-16 0:39
professionalAmin Esmaeily9-Oct-16 0:39 
QuestionHow to make line chart Pin
Radhakrishnan V16-Jun-15 2:19
Radhakrishnan V16-Jun-15 2:19 
AnswerRe: How to make line chart Pin
Amin Esmaeily23-Jun-15 23:55
professionalAmin Esmaeily23-Jun-15 23:55 
GeneralRe: How to make line chart Pin
Radhakrishnan V25-Jun-15 23:36
Radhakrishnan V25-Jun-15 23:36 
AnswerRe: How to make line chart Pin
Amin Esmaeily12-Jul-15 3:38
professionalAmin Esmaeily12-Jul-15 3:38 
QuestionNice post Esmaeily Pin
Radhakrishnan V16-Jun-15 2:16
Radhakrishnan V16-Jun-15 2:16 
QuestionRE:WPF Bar Chart as simple as possible Pin
Jacob Lee11-Nov-14 20:17
Jacob Lee11-Nov-14 20:17 
AnswerRe: WPF Bar Chart as simple as possible Pin
Amin Esmaeily13-Nov-14 0:41
professionalAmin Esmaeily13-Nov-14 0:41 
GeneralRe: WPF Bar Chart as simple as possible Pin
Radhakrishnan V25-Jun-15 23:40
Radhakrishnan V25-Jun-15 23:40 
QuestionWeird behaviour Pin
fireblade200927-Oct-14 9:08
fireblade200927-Oct-14 9:08 
AnswerRe: Weird behaviour Pin
Amin Esmaeily27-Oct-14 18:58
professionalAmin Esmaeily27-Oct-14 18:58 
QuestionIt looses the look and feel when scaled Pin
Sacha Barber4-Feb-14 2:19
Sacha Barber4-Feb-14 2:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.