How to implement a bar chart
This article shows you how to achieve a bar chart, the content is concise and easy to understand, can definitely brighten your eyes, through the detailed introduction of this article, I hope you can get something.
First, look at the effect first.
Second, the background of this article
Is there such a scenario: open source control libraries or paid control libraries, bar charts or bar charts are very powerful, but my business just doesn't match, that is, I have to design it myself? In this paper, through a simple implementation of a bar chart function, similar statistical charts can be modified in the future, the principle is similar.
Third, code implementation
The editor uses the WPF project created by .net Core 3.1. after creating a solution named "BarChart", add a WPF user control named "Bar", which is the single column in the figure above. Here is the Bar.xaml code.
Bar.xaml.cs code, mainly binding foreground color and background color, and column percentage value.
Using System.ComponentModel
Using System.Windows
Using System.Windows.Controls
Using System.Windows.Media
Namespace BarChart
{
/ / /
/ the interactive logic of BarChart.xaml
/ / /
Public partial class Bar: UserControl, INotifyPropertyChanged
{
Public event PropertyChangedEventHandler PropertyChanged
Private void NotifyPropertyChanged (string info)
{
If (PropertyChanged! = null)
{
PropertyChanged (this, new PropertyChangedEventArgs (info))
}
}
Private double _ value
Public double Value
{
Get {return _ value;}
Set
{
_ value = value
UpdateBarHeight ()
NotifyPropertyChanged ("Value")
}
}
Private double maxValue
Public double MaxValue
{
Get {return maxValue;}
Set
{
MaxValue = value
UpdateBarHeight ()
NotifyPropertyChanged ("MaxValue")
}
}
Private double barHeight
Public double BarHeight
{
Get {return barHeight;}
Set
{
BarHeight = value
NotifyPropertyChanged ("BarHeight")
}
}
Private Brush color
Public Brush Color
{
Get {return color;}
Set
{
Color = value
NotifyPropertyChanged ("Color")
}
}
Private void UpdateBarHeight ()
{
If (maxValue > 0)
{
Var percent = (_ value * 100) / maxValue
BarHeight = (percent * this.ActualHeight) / 100
}
}
Public Bar ()
{
InitializeComponent ()
This.DataContext = this
Color = Brushes.Black
}
Private void UserControl_Loaded (object sender, RoutedEventArgs e)
{
UpdateBarHeight ()
}
Private void Grid_SizeChanged (object sender, SizeChangedEventArgs e)
{
UpdateBarHeight ()
}
}
}
Main form MainWindow.xaml, add the displayed business data, currently only show the progress value, other tags as long as you understand the code, it is easy to add, such as each column, the color above shows a meaning name, below shows another meaning name.
The above content is how to implement a bar chart. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.