• WPF 常用功能整合


    目录

    WPF入门-1 行和列

    WPF入门-2 选项卡

    WPF入门-3 滚动条

    WPF LiveCharts 绘制图表

    WPF 百分比计算器

    WPF 获取 DataGrid 控件选中当前行某个列的值

    WPF LiveCharts 案例集合

    WPF 绑定数据和数据刷新

    WPF 解决 LiveCharts 中 Labels 显示不全的问题


    WPF入门-1 行和列

    微软官方资料:点击跳转

    划分模块

    有web前端开发经验的都知道,在做界面之前,通常会把界面分为几大的模块,然后再细化模块内部的界面布局,所以,学习WPF之前,也必须先弄懂这个

    前端代码

    1. <Window x:Class="WpfApplication1.MainWindow"
    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4. Title="MainWindow" Height="350" Width="800" Loaded="Window_Loaded">
    5. <Grid>
    6. <Grid.RowDefinitions>
    7. <RowDefinition Height="50"/>
    8. <RowDefinition Height="50"/>
    9. <RowDefinition Height="50"/>
    10. <RowDefinition Height="50"/>
    11. <RowDefinition Height="*"/>
    12. Grid.RowDefinitions>
    13. <Grid Grid.Row="0" Background="AntiqueWhite">
    14. Grid>
    15. <Grid Grid.Row="1" Background="Aqua">
    16. <Grid.ColumnDefinitions>
    17. <ColumnDefinition Width="300"/>
    18. <ColumnDefinition Width="300"/>
    19. Grid.ColumnDefinitions>
    20. <Grid Grid.Column="0" Background="BlueViolet">
    21. Grid>
    22. <Grid Grid.Column="1" Background="CadetBlue">
    23. Grid>
    24. Grid>
    25. <Grid Grid.Row="2" Background="Aquamarine">
    26. <Grid.ColumnDefinitions>
    27. <ColumnDefinition Width="300"/>
    28. <ColumnDefinition Width="300"/>
    29. Grid.ColumnDefinitions>
    30. Grid>
    31. <Grid Grid.Row="3" Background="Bisque">
    32. <Grid.ColumnDefinitions>
    33. <ColumnDefinition Width="300"/>
    34. <ColumnDefinition Width="300"/>
    35. Grid.ColumnDefinitions>
    36. Grid>
    37. <Grid Grid.Row="4" Background="Blue">
    38. Grid>
    39. Grid>
    40. Window>

    效果:

    这里是添加一行

    下面的 Grid.Row="0" 则表示第一行的布局,以及内部添加什么组件等

     

     在第二行的里面又添加了两列 ColumnDefinition,写法同添加行的一样

    WPF入门-2 选项卡

    1.主页面

    1. <Window x:Class="WpfApp1.MainWindow"
    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:local="clr-namespace:WpfApp1"
    7. mc:Ignorable="d"
    8. Title="MainWindow" Height="450" Width="800">
    9. <Grid>
    10. <TabControl>
    11. <TabItem Header="Page1">
    12. <Frame Source="/WpfApp1;component/Pages/Page1.xaml"/>
    13. TabItem>
    14. <TabItem Header="Page2">
    15. <Frame Source="/WpfApp1;component/Pages/Page2.xaml"/>
    16. TabItem>
    17. <TabItem Header="Page3">
    18. <Frame Source="/WpfApp1;component/Pages/Page3.xaml"/>
    19. TabItem>
    20. <TabItem Header="Page4">
    21. <Frame Source="/WpfApp1;component/Test/Page4.xaml"/>
    22. TabItem>
    23. TabControl>
    24. Grid>
    25. Window>

    指的是当前选项所指向的页面

    2.添加页

    在文件夹上点击鼠标右键

    添加完成后,如下

    在本次学习中,可以在页面中添加一些按钮,lable之类的,用来区分。

    其实这里用普通的界面也是可以的,只是要将窗体的最小化,最大化和关闭按钮 去掉,如下

    3.运行 

    WPF入门-3 滚动条

    主界面

    用微软官方的案例,不写任何代码

    1. <Window x:Class="WpfApplication1.MainWindow"
    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4. Title="MainWindow" Height="350" Width="800" Loaded="Window_Loaded">
    5. <Grid>
    6. <ScrollViewer HorizontalScrollBarVisibility="Auto">
    7. <StackPanel VerticalAlignment="Top" HorizontalAlignment="Left">
    8. <TextBlock TextWrapping="Wrap" Margin="0,0,0,20">请调整 Rectangle 组件大小,超过了窗体的大小,就会出现滚动条TextBlock>
    9. <Rectangle Fill="Green" Width="1500" Height="500">Rectangle>
    10. StackPanel>
    11. ScrollViewer>
    12. Grid>
    13. Window>

    ScrollViewer:滚动条组件

    StackPanel:栈面板,子元素超出部分,被隐藏,可以嵌套

    Rectangle:绘制矩形

    运行

    WPF LiveCharts 绘制图表

    一、新建项目

    新建一个项目 LiveChartBindingDemo,用这个名字,下面的代码你就可以完整的直接复制粘贴就好了,不必再修改。

    引入 LiveCharts 插件,在 NuGet 平台自己装就好了,我的版本是0.9.7,图片使用的编辑器是 Visual Studio 2013

    二、代码

    1.MainWindowViewModel

    1. using LiveCharts;
    2. using LiveCharts.Wpf;
    3. using System;
    4. using System.Collections.Generic;
    5. namespace LiveChartBindingDemo
    6. {
    7. public class MainWindowViewModel
    8. {
    9. SeriesCollection lineSeriesCollection = new SeriesCollection();
    10. SeriesCollection colunmSeriesCollection = new SeriesCollection();
    11. SeriesCollection pieSeriesCollection = new SeriesCollection();
    12. List<string> _lineXLabels = new List<string>();
    13. List<string> _columnXLabels = new List<string>();
    14. public MainWindowViewModel()
    15. {
    16. GetLineSeriesData();
    17. GetColunmSeriesData();
    18. GetPieSeriesData();
    19. }
    20. #region 属性
    21. ///
    22. /// 折线图集合
    23. ///
    24. public SeriesCollection LineSeriesCollection
    25. {
    26. get
    27. {
    28. return lineSeriesCollection;
    29. }
    30. set
    31. {
    32. lineSeriesCollection = value;
    33. }
    34. }
    35. ///
    36. /// 柱状图集合
    37. ///
    38. public SeriesCollection ColunmSeriesCollection
    39. {
    40. get
    41. {
    42. return colunmSeriesCollection;
    43. }
    44. set
    45. {
    46. colunmSeriesCollection = value;
    47. }
    48. }
    49. ///
    50. /// 饼图图集合
    51. ///
    52. public SeriesCollection PieSeriesCollection
    53. {
    54. get
    55. {
    56. return pieSeriesCollection;
    57. }
    58. set
    59. {
    60. pieSeriesCollection = value;
    61. }
    62. }
    63. ///
    64. /// 折线图X坐标
    65. ///
    66. public List<string> LineXLabels
    67. {
    68. get
    69. {
    70. return _lineXLabels;
    71. }
    72. set
    73. {
    74. _lineXLabels = value;
    75. }
    76. }
    77. ///
    78. /// 柱状图X坐标
    79. ///
    80. public List<string> ColumnXLabels
    81. {
    82. get
    83. {
    84. return _columnXLabels;
    85. }
    86. set
    87. {
    88. _columnXLabels = value;
    89. }
    90. }
    91. #endregion
    92. #region 方法
    93. void GetLineSeriesData()
    94. {
    95. List<string> titles = new List<string> { "苹果", "香蕉", "梨" };
    96. Listdouble>> values = new Listdouble>>
    97. {
    98. new List<double> { 30, 40, 60 },
    99. new List<double> { 20, 10, 50 },
    100. new List<double> { 10, 50, 30 }
    101. };
    102. List<string> _dates = new List<string>();
    103. _dates = GetCurrentMonthDates();
    104. for (int i = 0; i < titles.Count; i++)
    105. {
    106. LineSeries lineseries = new LineSeries();
    107. lineseries.DataLabels = true;
    108. lineseries.Title = titles[i];
    109. lineseries.Values = new ChartValues<double>(values[i]);
    110. LineXLabels.Add(_dates[i]);
    111. LineSeriesCollection.Add(lineseries);
    112. }
    113. }
    114. void GetColunmSeriesData()
    115. {
    116. List<string> titles = new List<string> { "Edge", "Chrome", "Firefox", "Other" };
    117. List<double> columnValues = new List<double> { 10, 70, 15, 5 };
    118. for (int i = 0; i < titles.Count; i++)
    119. {
    120. ColumnXLabels.Add(titles[i]);
    121. }
    122. ColumnSeries colunmseries = new ColumnSeries();
    123. colunmseries.DataLabels = true;
    124. colunmseries.Title = "占额";
    125. colunmseries.Values = new ChartValues<double>(columnValues);
    126. ColunmSeriesCollection.Add(colunmseries);
    127. }
    128. void GetPieSeriesData()
    129. {
    130. List<string> titles = new List<string> { "C#", "Java", "Python" };
    131. List<double> pieValues = new List<double> { 60, 30, 10 };
    132. ChartValues<double> chartvalue = new ChartValues<double>();
    133. for (int i = 0; i < titles.Count; i++)
    134. {
    135. chartvalue = new ChartValues<double>();
    136. chartvalue.Add(pieValues[i]);
    137. PieSeries series = new PieSeries();
    138. series.DataLabels = true;
    139. series.Title = titles[i];
    140. series.Values = chartvalue;
    141. PieSeriesCollection.Add(series);
    142. }
    143. }
    144. void ThreeColumnData()
    145. {
    146. List<string> titles = new List<string> { "苹果", "香蕉", "梨" };
    147. //三列示例数据
    148. Listdouble>> threeColunmValues = new Listdouble>>
    149. {
    150. new List<double> { 30, 40, 60 },
    151. new List<double> { 20, 10, 50 },
    152. new List<double> { 10, 50, 30 }
    153. };
    154. for (int i = 0; i < titles.Count; i++)
    155. {
    156. ColumnSeries colunmseries = new ColumnSeries();
    157. colunmseries.DataLabels = true;
    158. colunmseries.Title = titles[i];
    159. colunmseries.Values = new ChartValues<double>(threeColunmValues[i]);
    160. ColunmSeriesCollection.Add(colunmseries);
    161. }
    162. }
    163. ///
    164. /// 获取当前月的每天的日期
    165. ///
    166. /// 日期集合
    167. List<string> GetCurrentMonthDates()
    168. {
    169. List<string> dates = new List<string>();
    170. DateTime dt = DateTime.Now;
    171. int year = dt.Year;
    172. int mouth = dt.Month;
    173. int days = DateTime.DaysInMonth(year, mouth);
    174. //本月第一天时间
    175. DateTime dt_First = dt.AddDays(1 - (dt.Day));
    176. dates.Add(String.Format("{0:d}", dt_First.Date));
    177. for (int i = 1; i < days; i++)
    178. {
    179. DateTime temp = dt_First.AddDays(i);
    180. dates.Add(String.Format("{0:d}", temp.Date));
    181. }
    182. return dates;
    183. }
    184. #endregion
    185. }
    186. }

    2.前端代码 MainWindow.xaml

    1. <Window x:Class="LiveChartBindingDemo.MainWindow"
    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:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
    6. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    7. xmlns:local="clr-namespace:LiveChartBindingDemo"
    8. mc:Ignorable="d"
    9. Title="MainWindow"
    10. Height="720"
    11. Width="1280">
    12. <UniformGrid>
    13. <lvc:CartesianChart Series="{Binding LineSeriesCollection}"
    14. LegendLocation="Right">
    15. <lvc:CartesianChart.AxisY>
    16. <lvc:Axis>lvc:Axis>
    17. lvc:CartesianChart.AxisY>
    18. <lvc:CartesianChart.AxisX>
    19. <lvc:Axis Labels="{Binding LineXLabels}">lvc:Axis>
    20. lvc:CartesianChart.AxisX>
    21. lvc:CartesianChart>
    22. <lvc:CartesianChart Series="{Binding ColunmSeriesCollection}" LegendLocation="Right">
    23. <lvc:CartesianChart.AxisX>
    24. <lvc:Axis Labels="{Binding ColumnXLabels}">lvc:Axis>
    25. lvc:CartesianChart.AxisX>
    26. <lvc:CartesianChart.AxisY>
    27. <lvc:Axis>lvc:Axis>
    28. lvc:CartesianChart.AxisY>
    29. lvc:CartesianChart>
    30. <lvc:PieChart LegendLocation="Bottom" Series="{Binding PieSeriesCollection}" DataClick="Chart_OnDataClick" Hoverable="False">
    31. <lvc:PieChart.DataTooltip>
    32. <lvc:DefaultTooltip BulletSize="10">lvc:DefaultTooltip>
    33. lvc:PieChart.DataTooltip>
    34. lvc:PieChart>
    35. UniformGrid>
    36. Window>

    3.后端代码 MainWindow.xaml.cs

    1. using LiveCharts;
    2. using LiveCharts.Wpf;
    3. using System.Windows;
    4. namespace LiveChartBindingDemo
    5. {
    6. ///
    7. /// MainWindow.xaml 的交互逻辑
    8. ///
    9. public partial class MainWindow : Window
    10. {
    11. MainWindowViewModel mainWindowViewModel = new MainWindowViewModel();
    12. public MainWindow()
    13. {
    14. InitializeComponent();
    15. this.DataContext = mainWindowViewModel;
    16. }
    17. private void Chart_OnDataClick(object sender, ChartPoint chartpoint)
    18. {
    19. var chart = (LiveCharts.Wpf.PieChart)chartpoint.ChartView;
    20. //clear selected slice.
    21. foreach (PieSeries series in chart.Series)
    22. series.PushOut = 0;
    23. var selectedSeries = (PieSeries)chartpoint.SeriesView;
    24. selectedSeries.PushOut = 8;
    25. }
    26. }
    27. }

    以上就是所有的完整代码了,项目结构如下:

    三、运行

    WPF 百分比计算器

    设计了一个小工具,界面如下:

     

     xaml

    1. <Window x:Class="WpfApplication1.MainWindow"
    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4. ResizeMode ="CanMinimize" WindowStartupLocation="CenterScreen"
    5. Title="百分比计算器" Height="200" Width="300" Loaded="Window_Loaded">
    6. <Grid>
    7. <Label Content="总数量:" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="36,21,0,0" />
    8. <Label Content="你的数量:" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="36,51,0,0"/>
    9. <Label Content="结果:" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="36,76,0,0"/>
    10. <Label Name="Label_Result" Content="" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="110,76,0,0"/>
    11. <TextBox Name="TextBox_AllNum" Width="120" Height="23" Margin="110,25,0,0" TextWrapping="Wrap" Text="" HorizontalAlignment="Left" VerticalAlignment="Top" />
    12. <TextBox Name="TextBox_YourNum" Width="120" Height="23" Margin="110,53,0,0" TextWrapping="Wrap" Text="" HorizontalAlignment="Left" VerticalAlignment="Top" />
    13. <Button Content="计算" HorizontalAlignment="Left" Margin="110,127,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
    14. Grid>
    15. Window>

    后台代码:

    1. using System;
    2. using System.Windows;
    3. namespace WpfApplication1
    4. {
    5. public partial class MainWindow : Window
    6. {
    7. public MainWindow()
    8. {
    9. InitializeComponent();
    10. }
    11. private void Window_Loaded(object sender, RoutedEventArgs e)
    12. {
    13. }
    14. private void Button_Click(object sender, RoutedEventArgs e)
    15. {
    16. //总数量
    17. string s_allNum = this.TextBox_AllNum.Text;
    18. //你的数量
    19. string s_yourNum = this.TextBox_YourNum.Text;
    20. if (string.IsNullOrEmpty(s_allNum) || string.IsNullOrEmpty(s_yourNum))
    21. {
    22. MessageBox.Show("输入框不能为空");
    23. return;
    24. }
    25. double allNum = 0;
    26. double yourNum = 0;
    27. if (!double.TryParse(s_allNum, out allNum))
    28. {
    29. MessageBox.Show("总数量 输入框 输入的不是一个数字");
    30. return;
    31. }
    32. if (!double.TryParse(s_yourNum, out yourNum))
    33. {
    34. MessageBox.Show("你的数量 输入框 输入的不是一个数字");
    35. return;
    36. }
    37. if (yourNum > allNum)
    38. {
    39. MessageBox.Show("你的数量 不能大于 总数");
    40. return;
    41. }
    42. double result = (yourNum / allNum) * 100;
    43. this.Label_Result.Content = string.Format("{0}%", Math.Round(result, 4));
    44. }
    45. }
    46. }

    效果:

     

    WPF 获取 DataGrid 控件选中当前行某个列的值

    先新建一个工程,界面如下:

    这个项目按我之前写的例子上加的,链接:点击跳转 

    其实原来的项目也可以不用管,怎么获取DataGrid中的值才是本章的重点,

    在DataGrid 下面添加一个按钮,按钮的点击事件如下:

    1. private void Button_Click(object sender, RoutedEventArgs e)
    2. {
    3. string value = GetSelectedRow(MyDataGrid, "Name");
    4. Console.WriteLine(value);
    5. }

    封装获取点击行,某个列的值的方法

    1. ///
    2. /// 获取DataGrid控件选中当前行某个列的值
    3. ///
    4. /// DataGrid控件
    5. /// 列的名字
    6. /// 选中行列的值,参数错误则返回null
    7. public string GetSelectedRow(DataGrid dataGrid, string readName)
    8. {
    9. if (dataGrid == null)
    10. {
    11. Console.WriteLine("dataGrid 不能为空");
    12. return null;
    13. }
    14. if (string.IsNullOrEmpty(readName))
    15. {
    16. Console.WriteLine("readName不能为空");
    17. return null;
    18. }
    19. if (dataGrid.SelectedItems.Count == 0)
    20. {
    21. Console.WriteLine("dataGrid未选中任何数据");
    22. return null;
    23. }
    24. if (dataGrid.SelectedItems.Count > 1)
    25. {
    26. Console.WriteLine("不支持选中多行,读取某一个数据");
    27. return null;
    28. }
    29. DataRowView dataRowView = dataGrid.SelectedCells[0].Item as DataRowView;
    30. if (dataRowView.Row.Table.Columns.Contains(readName))
    31. return dataRowView[readName].ToString();
    32. return null;
    33. }

    运行:

    先选中一行,然后点击测试,成功获取到值

    WPF LiveCharts 案例集合

    学习资料

    LiveCharts官方文档:点击跳转

    一、柱状图

    案例1

    效果:

    前端

    1. <Window x:Class="WpfApplication1.MainWindow"
    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:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
    7. Title="MainWindow" Width="700" Height="400" >
    8. <Grid>
    9. <lvc:CartesianChart Margin="20,75,20,15">
    10. <lvc:CartesianChart.AxisX>
    11. <lvc:Axis FontSize="12" Labels="{Binding Path=StorageLabels}" Title="库位" LabelsRotation="20">
    12. <lvc:Axis.Separator>
    13. <lvc:Separator Step="1" IsEnabled="False"/>
    14. lvc:Axis.Separator>
    15. lvc:Axis>
    16. lvc:CartesianChart.AxisX>
    17. <lvc:CartesianChart.AxisY>
    18. <lvc:Axis FontSize="12" Title="百分比" ShowLabels="True" LabelFormatter="{Binding Path=AxisPercentage}">
    19. <lvc:Axis.Separator>
    20. <lvc:Separator Stroke="#33ffffff" StrokeDashArray="10"/>
    21. lvc:Axis.Separator>
    22. lvc:Axis>
    23. lvc:CartesianChart.AxisY>
    24. <lvc:CartesianChart.Series>
    25. <lvc:ColumnSeries Values="{Binding Path=StoragePercentages}" DataLabels="True" LabelsPosition="Top"/>
    26. lvc:CartesianChart.Series>
    27. <lvc:CartesianChart.ChartLegend>
    28. <lvc:DefaultLegend BulletSize="12"/>
    29. lvc:CartesianChart.ChartLegend>
    30. lvc:CartesianChart>
    31. Grid>
    32. Window>

     后端

    1. using LiveCharts;
    2. using LiveCharts.Wpf;
    3. using System;
    4. using System.Windows;
    5. namespace WpfApplication1
    6. {
    7. ///
    8. /// Interaction logic for MainWindow.xaml
    9. ///
    10. public partial class MainWindow : Window
    11. {
    12. private Func<double, string> _axisPercentage;
    13. private string[] _storageLabels;
    14. private IChartValues _storagePercentages;
    15. public Func<double, string> AxisPercentage
    16. {
    17. get { return _axisPercentage; }
    18. set { _axisPercentage = value; }
    19. }
    20. public string[] StorageLabels
    21. {
    22. get { return _storageLabels; }
    23. set { _storageLabels = value; }
    24. }
    25. public IChartValues StoragePercentages
    26. {
    27. get { return _storagePercentages; }
    28. set { _storagePercentages = value; }
    29. }
    30. private void ShowStoragePercentageColumnChart()
    31. {
    32. StorageLabels = new[]
    33. {
    34. "单元一原料","单元一成品","单元二原料","单元二半成品","单元三原料","单元三半成品","单元四原料","单元四半成品"
    35. };
    36. AxisPercentage = val => val.ToString("P");
    37. StoragePercentages = new ChartValues<double> { 0.2, 0.5, 0.44, 0.88, 0.22, 0.6, 0.14, 0.09 };
    38. this.DataContext = this;
    39. }
    40. public MainWindow()
    41. {
    42. InitializeComponent();
    43. ShowStoragePercentageColumnChart();
    44. }
    45. }
    46. }

    案例2

    效果

     前端

    1. "Test1.MainWindow"
    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:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
    6. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    7. Title="MainWindow" Width="1280" Height="720" Loaded="Window_Loaded">
    8. "True" Values="{Binding Values2}" Panel.ZIndex="1">
    9. "True" Values="{Binding Values1}" Panel.ZIndex="1">

    后端

    1. using System.Windows;
    2. using LiveCharts;
    3. namespace Test1
    4. {
    5. ///
    6. /// MainWindow.xaml 的交互逻辑
    7. ///
    8. public partial class MainWindow : Window
    9. {
    10. public MainWindow()
    11. {
    12. InitializeComponent();
    13. }
    14. public ChartValues<double> Values1 { get; set; }
    15. public ChartValues<double> Values2 { get; set; }
    16. private void Window_Loaded(object sender, RoutedEventArgs e)
    17. {
    18. Values1 = new ChartValues<double> {3, 5, 2, 6, 2, 7, 1};
    19. Values2 = new ChartValues<double> {6, 2, 6, 3, 2, 7, 2};
    20. DataContext = this;
    21. }
    22. }
    23. }

    二、饼状图

    案例1

    效果

    前端

    1. <Window x:Class="LiveChartBindingDemo.MainWindow"
    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:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
    6. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    7. Title="MainWindow" Width="400" Height="300">
    8. <UniformGrid>
    9. <lvc:PieChart LegendLocation="Bottom" Series="{Binding PieSeriesCollection}" DataClick="Chart_OnDataClick" Hoverable="False">
    10. <lvc:PieChart.DataTooltip>
    11. <lvc:DefaultTooltip BulletSize="10">lvc:DefaultTooltip>
    12. lvc:PieChart.DataTooltip>
    13. lvc:PieChart>
    14. UniformGrid>
    15. Window>

    后端

    1. using LiveCharts;
    2. using LiveCharts.Wpf;
    3. using System;
    4. using System.Windows;
    5. namespace LiveChartBindingDemo
    6. {
    7. ///
    8. /// MainWindow.xaml 的交互逻辑
    9. ///
    10. public partial class MainWindow : Window
    11. {
    12. MainWindowViewModel mainWindowViewModel = new MainWindowViewModel();
    13. public MainWindow()
    14. {
    15. InitializeComponent();
    16. this.DataContext = mainWindowViewModel;
    17. }
    18. private void Chart_OnDataClick(object sender, ChartPoint chartpoint)
    19. {
    20. var chart = (LiveCharts.Wpf.PieChart)chartpoint.ChartView;
    21. foreach (PieSeries series in chart.Series)
    22. series.PushOut = 0;
    23. var selectedSeries = (PieSeries)chartpoint.SeriesView;
    24. selectedSeries.PushOut = 8;
    25. }
    26. }
    27. }

    绑定数据

    1. using LiveCharts;
    2. using LiveCharts.Wpf;
    3. using System;
    4. using System.Collections.Generic;
    5. using System.Windows;
    6. namespace LiveChartBindingDemo
    7. {
    8. public class MainWindowViewModel
    9. {
    10. SeriesCollection pieSeriesCollection = new SeriesCollection();
    11. public MainWindowViewModel()
    12. {
    13. GetPieSeriesData();
    14. }
    15. #region 属性
    16. ///
    17. /// 饼图图集合
    18. ///
    19. public SeriesCollection PieSeriesCollection
    20. {
    21. get { return pieSeriesCollection; }
    22. set { pieSeriesCollection = value; }
    23. }
    24. #endregion
    25. #region 方法
    26. void GetPieSeriesData()
    27. {
    28. List<string> titles = new List<string> { "C#", "Java", "Python" };
    29. List<double> pieValues = new List<double> { 60, 30, 10 };
    30. ChartValues<double> chartvalue = new ChartValues<double>();
    31. for (int i = 0; i < titles.Count; i++)
    32. {
    33. chartvalue = new ChartValues<double>();
    34. chartvalue.Add(pieValues[i]);
    35. PieSeries series = new PieSeries();
    36. series.DataLabels = true;
    37. series.Title = titles[i];
    38. series.Values = chartvalue;
    39. PieSeriesCollection.Add(series);
    40. }
    41. }
    42. #endregion
    43. }
    44. }

    三、折线图

    案例1

    效果

    前端

    1. <Window x:Class="LiveChartBindingDemo.MainWindow"
    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:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
    6. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    7. Title="MainWindow" Width="400" Height="300">
    8. <UniformGrid>
    9. <lvc:CartesianChart Series="{Binding LineSeriesCollection}" LegendLocation="Right">
    10. <lvc:CartesianChart.AxisY>
    11. <lvc:Axis>lvc:Axis>
    12. lvc:CartesianChart.AxisY>
    13. <lvc:CartesianChart.AxisX>
    14. <lvc:Axis Labels="{Binding LineXLabels}">lvc:Axis>
    15. lvc:CartesianChart.AxisX>
    16. lvc:CartesianChart>
    17. UniformGrid>
    18. Window>

    后端

    1. using LiveCharts;
    2. using LiveCharts.Wpf;
    3. using System;
    4. using System.Windows;
    5. namespace LiveChartBindingDemo
    6. {
    7. ///
    8. /// MainWindow.xaml 的交互逻辑
    9. ///
    10. public partial class MainWindow : Window
    11. {
    12. MainWindowViewModel mainWindowViewModel = new MainWindowViewModel();
    13. public MainWindow()
    14. {
    15. InitializeComponent();
    16. this.DataContext = mainWindowViewModel;
    17. }
    18. }
    19. }

     MainWindowViewModel

    1. using LiveCharts;
    2. using LiveCharts.Wpf;
    3. using System;
    4. using System.Collections.Generic;
    5. using System.Windows;
    6. namespace LiveChartBindingDemo
    7. {
    8. public class MainWindowViewModel
    9. {
    10. private SeriesCollection lineSeriesCollection = new SeriesCollection();
    11. private List<string> _lineXLabels = new List<string>();
    12. public MainWindowViewModel()
    13. {
    14. GetLineSeriesData();
    15. }
    16. #region 属性
    17. ///
    18. /// 折线图集合
    19. ///
    20. public SeriesCollection LineSeriesCollection
    21. {
    22. get { return lineSeriesCollection; }
    23. set { lineSeriesCollection = value; }
    24. }
    25. ///
    26. /// 折线图X坐标
    27. ///
    28. public List<string> LineXLabels
    29. {
    30. get { return _lineXLabels; }
    31. set { _lineXLabels = value; }
    32. }
    33. #endregion
    34. #region 方法
    35. private void GetLineSeriesData()
    36. {
    37. List<string> titles = new List<string> { "苹果", "香蕉", "梨" };
    38. Listdouble>> values = new Listdouble>>
    39. {
    40. new List<double> { 30, 40, 60 },
    41. new List<double> { 20, 10, 50 },
    42. new List<double> { 10, 50, 30 }
    43. };
    44. List<string> _dates = new List<string>();
    45. _dates = GetCurrentMonthDates();
    46. for (int i = 0; i < titles.Count; i++)
    47. {
    48. LineSeries lineseries = new LineSeries();
    49. lineseries.DataLabels = true;
    50. lineseries.Title = titles[i];
    51. lineseries.Values = new ChartValues<double>(values[i]);
    52. LineXLabels.Add(_dates[i]);
    53. LineSeriesCollection.Add(lineseries);
    54. }
    55. }
    56. ///
    57. /// 获取当前月的每天的日期
    58. ///
    59. /// 日期集合
    60. private List<string> GetCurrentMonthDates()
    61. {
    62. List<string> dates = new List<string>();
    63. DateTime dt = DateTime.Now;
    64. int year = dt.Year;
    65. int mouth = dt.Month;
    66. int days = DateTime.DaysInMonth(year, mouth);
    67. //本月第一天时间
    68. DateTime dt_First = dt.AddDays(1 - (dt.Day));
    69. dates.Add(String.Format("{0:d}", dt_First.Date));
    70. for (int i = 1; i < days; i++)
    71. {
    72. DateTime temp = dt_First.AddDays(i);
    73. dates.Add(String.Format("{0:d}", temp.Date));
    74. }
    75. return dates;
    76. }
    77. #endregion
    78. }
    79. }

    WPF 绑定数据和数据刷新

    1.ViewModelBase

    主要用做前端界面更新数据的通知

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Text;
    5. using System.Threading.Tasks;
    6. namespace WpfApplication2
    7. {
    8. ///
    9. /// 实现了属性更改通知的基类
    10. ///
    11. public class ViewModelBase : System.ComponentModel.INotifyPropertyChanged
    12. {
    13. public virtual event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
    14. ///
    15. /// 属性值变化时发生
    16. ///
    17. ///
    18. protected virtual void OnPropertyChanged(string propertyName)
    19. {
    20. if (this.PropertyChanged != null)
    21. this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
    22. }
    23. ///
    24. /// 属性值变化时发生
    25. ///
    26. ///
    27. protected virtual void OnPropertyChanged<T>(System.Linq.Expressions.Expression> propertyExpression)
    28. {
    29. var propertyName = (propertyExpression.Body as System.Linq.Expressions.MemberExpression).Member.Name;
    30. this.OnPropertyChanged(propertyName);
    31. }
    32. }
    33. }

    2.前端代码

    1. "WpfApplication2.MainWindow"
    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4. Title="MainWindow" Width="300" Height="200" Loaded="Window_Loaded">

    3.后端代码

    1. using System;
    2. using System.ComponentModel;
    3. using System.Windows;
    4. namespace WpfApplication2
    5. {
    6. ///
    7. /// MainWindow.xaml 的交互逻辑
    8. ///
    9. public partial class MainWindow : Window
    10. {
    11. public MainWindow()
    12. {
    13. InitializeComponent();
    14. }
    15. private Test Tests = new Test();
    16. private void Window_Loaded(object sender, RoutedEventArgs e)
    17. {
    18. Tests.MyLable = "默认值";
    19. this.DataContext = Tests;
    20. }
    21. private void Button_Click(object sender, RoutedEventArgs e)
    22. {
    23. Random r = new Random();
    24. int randomNum = r.Next(1, 100);
    25. string content = string.Format("随机数:{0}", randomNum);
    26. Tests.MyLable = content;
    27. }
    28. }
    29. public class Test : ViewModelBase
    30. {
    31. private string myLable;
    32. public string MyLable
    33. {
    34. get { return myLable; }
    35. set { myLable = value; this.OnPropertyChanged("MyLable"); }
    36. }
    37. }
    38. }

    在这里新建了一个类,并继承了 ViewModeBase,在 MyLable  Set 访问器中,加入了 数据更新通知,另外 this.DataContext = Tests; 这句是给前端数据绑定的类

    测试

    运行后,界面如下:

    点击 Test 按钮,可以看到,数据成功在后台更新了

    WPF 解决 LiveCharts 中 Labels 显示不全的问题

    在显示柱状图时,绑定的 Labels 数组明明是完整的,但是在图表中就是只显示不完整,如下图:

    底下的列名,有的显示,有的不显示。

    网上查了一圈,也没看到什么有用的例子,后面终于在github 上看到了答案

    有兴趣的可以去看看:点击跳转

    当然,下面也会介绍解决的方法。

    二、源代码

    这里是上面的图片原代码

    前端:

    1. <Window x:Class="WpfApplication1.MainWindow"
    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4. xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
    5. Title="MainWindow" Height="350" Width="525">
    6. <Grid>
    7. <lvc:CartesianChart Name="LineChart" LegendLocation="top" >
    8. <lvc:CartesianChart.AxisY>
    9. <lvc:Axis Title="Sales" >lvc:Axis>
    10. lvc:CartesianChart.AxisY>
    11. <lvc:CartesianChart.AxisX>
    12. <lvc:AxesCollection>
    13. <lvc:Axis Labels="{Binding Labels}"/>
    14. lvc:AxesCollection>
    15. lvc:CartesianChart.AxisX>
    16. lvc:CartesianChart>
    17. Grid>
    18. Window>

    后端代码:

    1. using LiveCharts;
    2. using LiveCharts.Wpf;
    3. using System.Windows;
    4. namespace WpfApplication1
    5. {
    6. ///
    7. /// MainWindow.xaml 的交互逻辑
    8. ///
    9. public partial class MainWindow : Window
    10. {
    11. private SeriesCollection seriesCollection = new SeriesCollection();
    12. public string[] Labels { get; set; }
    13. public MainWindow()
    14. {
    15. InitializeComponent();
    16. Labels = new string[] { "第一列", "第二列", "第三列", "第四列", "第五列", "第六列", "第七列", "第八列", "第九列", "第十列" };
    17. DataContext = this;
    18. LoadLineChart();
    19. }
    20. private void LoadLineChart()
    21. {
    22. seriesCollection = new SeriesCollection
    23. {
    24. new ColumnSeries
    25. {
    26. Title = "1988",
    27. Values = new ChartValues<double> { 10, 50, 39, 50, 5, 10, 15, 20, 25, 30 }
    28. }
    29. };
    30. LineChart.Series = seriesCollection;
    31. }
    32. }
    33. }

    三、解决问题

    只需要改前端就行了,如下,重点是加入 Separator标签,和 Step=“1” 这句。

    1. <Window x:Class="WpfApplication1.MainWindow"
    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4. xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
    5. Title="MainWindow" Height="350" Width="525">
    6. <Grid>
    7. <lvc:CartesianChart Name="LineChart" LegendLocation="top" >
    8. <lvc:CartesianChart.AxisY>
    9. <lvc:Axis Title="Sales" >lvc:Axis>
    10. lvc:CartesianChart.AxisY>
    11. <lvc:CartesianChart.AxisX>
    12. <lvc:AxesCollection>
    13. <lvc:Axis Labels="{Binding Labels}">
    14. <lvc:Axis.Separator>
    15. <lvc:Separator Step="1" />
    16. lvc:Axis.Separator>
    17. lvc:Axis>
    18. lvc:AxesCollection>
    19. lvc:CartesianChart.AxisX>
    20. lvc:CartesianChart>
    21. Grid>
    22. Window>

    运行测试:

    可以看到,完美的解决了问题

    end

  • 相关阅读:
    设计模式——行为型设计模式
    数字IC验证——PSS可移植测试用例
    vue pc商城项目 ----------登录
    华为OD机试真题【最多颜色的车辆】
    在Linux下,转换来自windos文本中的换行符\r\n为\n
    css样式操作、动画操作
    猿创征文|大数据之离线数据处理总结+思维导图(全面总结)
    css 相关知识点汇总
    365天挑战LeetCode1000题——Day 046 生成每种字符都是奇数个的字符串 + 两数相加 + 有效的括号
    (手撕)数据结构--->堆
  • 原文地址:https://blog.csdn.net/qq_38693757/article/details/125993367