Telerik Silverlight 之Charting控制元件的使用

暖楓無敵發表於2012-10-19

效果還是不錯的,還能設定動態載入效果,如下圖:

                                                                                                               

圖表樣式的資原始檔 RadChartStyle.xaml,內容如下:

<ResourceDictionary
	xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:System="clr-namespace:System;assembly=mscorlib"
    xmlns:Telerik_Windows_Controls_Charting="clr-namespace:Telerik.Windows.Controls.Charting;assembly=Telerik.Windows.Controls.Charting">
    <!-- 應該在此定義資源字典條目。-->
    <SolidColorBrush x:Key="ChartTitleBackground" Color="#FF226AB8"/>
    <SolidColorBrush x:Key="ChartTitleBorderBrush" Color="#FFFDFDFD"/>
    <SolidColorBrush x:Key="ChartTitleOuterBorderBrush" Color="#FF226AB8"/>
    <Thickness x:Key="ChartTitleBorderThickness">0</Thickness>
    <Thickness x:Key="ChartTitleOuterBorderThickness">0,0,0,0</Thickness>
    <Thickness x:Key="ChartTitlePadding">7</Thickness>
    <SolidColorBrush x:Key="ChartTitleForeground" Color="White"/>
    <System:Double x:Key="ChartTitleFontSize">12</System:Double>
    <FontWeight x:Key="ChartTitleFontWeight">Bold</FontWeight>
    <Style x:Key="ChartTitleStyle1" TargetType="Telerik_Windows_Controls_Charting:ChartTitle">
        <Setter Property="HorizontalContentAlignment" Value="Center"/>
        <Setter Property="Background" Value="{StaticResource ChartTitleBackground}"/>
        <Setter Property="BorderBrush" Value="{StaticResource ChartTitleBorderBrush}"/>
        <Setter Property="OuterBorderBrush" Value="{StaticResource ChartTitleOuterBorderBrush}"/>
        <Setter Property="BorderThickness" Value="{StaticResource ChartTitleBorderThickness}"/>
        <Setter Property="OuterBorderThickness" Value="{StaticResource ChartTitleOuterBorderThickness}"/>
        <Setter Property="Padding" Value="{StaticResource ChartTitlePadding}"/>
        <Setter Property="Foreground" Value="{StaticResource ChartTitleForeground}"/>
        <Setter Property="FontSize" Value="{StaticResource ChartTitleFontSize}"/>
        <Setter Property="FontWeight" Value="{StaticResource ChartTitleFontWeight}"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Telerik_Windows_Controls_Charting:ChartTitle">
                    <Border CornerRadius="5" BorderBrush="{TemplateBinding OuterBorderBrush}" BorderThickness="{TemplateBinding OuterBorderThickness}">
                        <Border  CornerRadius="5" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" >
                            <ContentControl HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" FontFamily="{TemplateBinding FontFamily}" FontSize="12" FontStyle="{TemplateBinding FontStyle}" FontWeight="{TemplateBinding FontWeight}" Foreground="{TemplateBinding Foreground}" Content="{TemplateBinding Content}" Height="15"/>
                        </Border>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

App.xaml 主要是新增了資源字典,用於引入圖表樣式的資原始檔RadChartStyle.xaml

 

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
             x:Class="DCharting.App"
             >
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="RadChartStyle.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>


 

--------------------------------------------------------------------------折線圖-----------------------------------------------------------------------------------------------------

<UserControl x:Class="DCharting.LineChart"
    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:Telerik_Windows_Controls="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.Charting"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <UserControl.Resources>
        <Style x:Key="GridLineStyle"
       TargetType="Line">
            <Setter Property="Stroke"
           Value="Black" />
            <Setter Property="StrokeThickness"
           Value="1" />
        </Style>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot">
        <Telerik_Windows_Controls:RadChart x:Name="radChart" Content="RadChart" Foreground="#FFFBF9F9" TitleStyle="{StaticResource ChartTitleStyle1}"/>
        <Button x:Name="prt" Content="列印" HorizontalAlignment="Right" Height="29" Margin="0,4,7,0" VerticalAlignment="Top" Width="83" RenderTransformOrigin="3.886,0.397" FontSize="13.333"/>
    </Grid>
</UserControl>


 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Telerik.Windows.Controls.Charting;
using System.Windows.Printing;
using DCharting.ServiceReference1;

namespace DCharting
{
    public partial class LineChart : UserControl
    {
        private Random rand = new Random(DateTime.Now.Millisecond);

        public LineChart()
        {
            InitializeComponent();
            setChart(DM.DFAGNM + "溫度過程線");
            ConfigureChart();
            prt.Click += new RoutedEventHandler(prt_Click);
        }


        void prt_Click(object sender, RoutedEventArgs e)
        {
            PrintDocument prtDoc = new PrintDocument();
            prtDoc.PrintPage += new EventHandler<PrintPageEventArgs>(prtDoc_PrintPage);
            prtDoc.Print("溫度過程線");
        }

        private void prtDoc_PrintPage(object sender, PrintPageEventArgs e)
        {
            e.PageVisual = radChart;
        }

        private void ConfigureChart()
        {
            LineSeriesDefinition lineSeries = new LineSeriesDefinition();
            lineSeries.ShowItemLabels = false;
            lineSeries.ShowPointMarks = false;

            //SeriesMapping dataMapping = new SeriesMapping();
            //dataMapping.SeriesDefinition = lineSeries;
            //dataMapping.ItemMappings.Add(new ItemMapping("XValue", DataPointMember.XValue));
            //dataMapping.ItemMappings.Add(new ItemMapping("YValue", DataPointMember.YValue));
            //dataMapping.ItemMappings[1].SamplingFunction = ChartSamplingFunction.KeepExtremes;

            //radChart.SeriesMappings.Add(dataMapping);
            //radChart.DefaultView.ChartArea.ZoomScrollSettingsX.ScrollMode = ScrollMode.ScrollAndZoom;
            // radChart.DefaultView.ChartArea.ZoomScrollSettingsY.ScrollMode = ScrollMode.ScrollAndZoom;

            radChart.DefaultView.ChartArea.NoDataString = "正在載入圖形資料,請等待...";


            radChart.DefaultView.ChartArea.Padding = new Thickness(5, 10, 20, 5);

            radChart.DefaultView.ChartArea.LabelFormatBehavior = LabelFormatBehavior.None;
            radChart.SamplingSettings.SamplingThreshold = 3000; //此屬性用於控制動畫的時間
            radChart.DefaultView.ChartArea.EnableAnimations = true; //此屬性控制動畫效果
            radChart.DefaultView.ChartArea.EnableTransitionAnimations = true;

            radChart.DefaultView.ChartLegend.Visibility = Visibility.Collapsed;
        }

        private void setChart(string title)
        {
            radChart.DefaultView.ChartTitle.Content = title;
            this.radChart.DefaultSeriesDefinition.LegendDisplayMode = LegendDisplayMode.None;
            // this.radChart.DefaultView.ChartLegendPosition = Telerik.Windows.Controls.Dock.Bottom;
            radChart.DefaultView.ChartArea.AxisX.MajorGridLinesVisibility = Visibility.Visible;
            radChart.DefaultView.ChartArea.AxisY.StripLinesVisibility = Visibility.Collapsed;
            radChart.DefaultView.ChartArea.AxisY.MajorGridLinesVisibility = Visibility.Visible;
            radChart.DefaultView.ChartArea.AxisY.MinorGridLinesVisibility = Visibility.Collapsed;
            this.radChart.DefaultView.ChartArea.AxisY.AxisStyles.GridLineStyle = this.Resources["GridLineStyle"] as Style;
            this.radChart.DefaultView.ChartArea.AxisX.AxisStyles.GridLineStyle = this.Resources["GridLineStyle"] as Style;

            radChart.DefaultView.ChartTitle.HorizontalAlignment = HorizontalAlignment.Center;

            radChart.DefaultView.ChartArea.AxisX.AutoRange = true;
            radChart.DefaultView.ChartArea.AxisX.StripLinesVisibility = Visibility.Visible;
            radChart.DefaultView.ChartArea.AxisY.StripLinesVisibility = Visibility.Visible;
            radChart.DefaultView.ChartTitle.HorizontalAlignment = HorizontalAlignment.Center;
            radChart.DefaultView.ChartLegend.Header = "圖例";
            radChart.DefaultView.ChartLegend.UseAutoGeneratedItems = true;
            //X軸標題
            radChart.DefaultView.ChartArea.AxisX.Title = "時間";
            radChart.DefaultView.ChartArea.AxisX.LayoutMode = AxisLayoutMode.Between;
            //Y軸標題
            radChart.DefaultView.ChartArea.AxisY.Title = "溫度";
            addSerise();
        }

        private void addSerise()
        {
            getDataSoapClient client = new getDataSoapClient();
            client.getAllTemperatureCompleted += new EventHandler<getAllTemperatureCompletedEventArgs>(client_getAllTemperatureCompleted);
            client.getAllTemperatureAsync();
        }

        void client_getAllTemperatureCompleted(object sender, getAllTemperatureCompletedEventArgs e)
        {
            int index = 0;
            DataSeries series = new DataSeries();
            series.Definition = new LineSeriesDefinition();
            series.LegendLabel = "溫度";
            if (e.Error == null)
            {
                System.Collections.ObjectModel.ObservableCollection<Temperature> trees = e.Result;
                foreach (Temperature item in trees)
                {
                    if (index < 20)
                    {
                        index++;
                        series.Add(new DataPoint(item.StationName, System.Convert.ToDouble(item.MaxTemp)));
                    }
                    else
                    {
                        break;
                    }
                }
            }
            radChart.DefaultView.ChartArea.DataSeries.Add(series);
        }

        private void chart_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            //string year = ((ComboBoxItem)chart.SelectedItem).Content.ToString();
            //setchart(year);
        }
    }
}


 

------------------------------------------------------------------------------------柱狀圖-----------------------------------------------------------------------

 

 

<UserControl x:Class="DCharting.MainPage"
    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"
    mc:Ignorable="d"
    xmlns:Telerik_Windows_Controls="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.Charting"
    d:DesignHeight="300" d:DesignWidth="400">
    <UserControl.Resources>
        <Style x:Key="GridLineStyle" TargetType="Line">
            <Setter Property="Stroke" Value="Black" />
            <Setter Property="StrokeThickness" Value="1" />
        </Style>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="White">
        <Telerik_Windows_Controls:RadChart x:Name="radChart" Content="RadChart" Foreground="#FFFBF9F9" TitleStyle="{StaticResource ChartTitleStyle1}"/>
        <Button x:Name="prt" Content="列印" HorizontalAlignment="Right" Height="29" Margin="0,4,7,0" VerticalAlignment="Top" Width="83" RenderTransformOrigin="3.886,0.397" FontSize="13.333"/>
    </Grid>
</UserControl>


 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Telerik.Windows.Controls.Charting;
using System.Windows.Printing;
using DCharting.ServiceReference1;

namespace DCharting
{
    public partial class MainPage : UserControl
    {
        //產生一個隨機數
        private Random rand = new Random(DateTime.Now.Millisecond);

        public MainPage()
        {
            InitializeComponent();
            setChart(DM.DFAGNM + "溫度柱柱狀圖");
            ConfigureChart();
            prt.Click += new RoutedEventHandler(prt_Click);
        }

        void prt_Click(object sender, RoutedEventArgs e)
        {
            PrintDocument prtDoc = new PrintDocument();
            prtDoc.PrintPage += new EventHandler<PrintPageEventArgs>(prtDoc_PrintPage);
            prtDoc.Print("溫度柱柱狀圖");

        }

        private void prtDoc_PrintPage(object sender, PrintPageEventArgs e)
        {
            e.PageVisual = radChart;

        }


        private void ConfigureChart()
        {
            LineSeriesDefinition lineSeries = new LineSeriesDefinition();
            lineSeries.ShowItemLabels = false;
            lineSeries.ShowPointMarks = false;

            //SeriesMapping dataMapping = new SeriesMapping();
            //dataMapping.SeriesDefinition = lineSeries;
            //dataMapping.ItemMappings.Add(new ItemMapping("XValue", DataPointMember.XValue));
            //dataMapping.ItemMappings.Add(new ItemMapping("YValue", DataPointMember.YValue));
            //dataMapping.ItemMappings[1].SamplingFunction = ChartSamplingFunction.KeepExtremes;

            //radChart.SeriesMappings.Add(dataMapping);
            radChart.DefaultView.ChartArea.ZoomScrollSettingsX.ScrollMode = ScrollMode.ScrollAndZoom;
            radChart.DefaultView.ChartArea.ZoomScrollSettingsY.ScrollMode = ScrollMode.ScrollAndZoom;

            radChart.DefaultView.ChartArea.NoDataString = "正在載入圖形資料,請等待...";


            radChart.DefaultView.ChartArea.Padding = new Thickness(5, 10, 20, 5);

            radChart.DefaultView.ChartArea.LabelFormatBehavior = LabelFormatBehavior.None;
            radChart.SamplingSettings.SamplingThreshold = 1000;  //此屬性用於控制動畫的時間
            radChart.DefaultView.ChartArea.EnableAnimations = true; //此屬性控制動畫效果
            radChart.DefaultView.ChartArea.EnableTransitionAnimations = true;

            radChart.DefaultView.ChartLegend.Visibility = Visibility.Collapsed;
        }

        private void setChart(string title)
        {
            radChart.DefaultView.ChartTitle.Content = title;
            this.radChart.DefaultSeriesDefinition.LegendDisplayMode = LegendDisplayMode.None;
            // this.radChart.DefaultView.ChartLegendPosition = Telerik.Windows.Controls.Dock.Bottom;
            radChart.DefaultView.ChartArea.AxisX.MajorGridLinesVisibility = Visibility.Visible;
            radChart.DefaultView.ChartArea.AxisY.StripLinesVisibility = Visibility.Collapsed;
            radChart.DefaultView.ChartArea.AxisY.MajorGridLinesVisibility = Visibility.Visible;
            radChart.DefaultView.ChartArea.AxisY.MinorGridLinesVisibility = Visibility.Collapsed;
            this.radChart.DefaultView.ChartArea.AxisY.AxisStyles.GridLineStyle = this.Resources["GridLineStyle"] as Style;
            this.radChart.DefaultView.ChartArea.AxisX.AxisStyles.GridLineStyle = this.Resources["GridLineStyle"] as Style;

            radChart.DefaultView.ChartTitle.HorizontalAlignment = HorizontalAlignment.Center;

            radChart.DefaultView.ChartArea.AxisX.AutoRange = true;
            radChart.DefaultView.ChartArea.AxisX.StripLinesVisibility = Visibility.Visible;
            radChart.DefaultView.ChartArea.AxisY.StripLinesVisibility = Visibility.Visible;
            radChart.DefaultView.ChartTitle.HorizontalAlignment = HorizontalAlignment.Center;
            radChart.DefaultView.ChartLegend.Header = "圖例";
            radChart.DefaultView.ChartLegend.UseAutoGeneratedItems = true;
            //X軸標題
            radChart.DefaultView.ChartArea.AxisX.Title = "地點";
            radChart.DefaultView.ChartArea.AxisX.LayoutMode = AxisLayoutMode.Between;
            //Y軸標題
            radChart.DefaultView.ChartArea.AxisY.Title = "溫度";
            addSerise();

        }

        /// <summary>
        /// 通過WebService動態獲取資料
        /// </summary>
        private void addSerise()
        {
            getDataSoapClient client = new getDataSoapClient();
            client.getAllTemperatureCompleted += new EventHandler<getAllTemperatureCompletedEventArgs>(client_getAllTemperatureCompleted);
            client.getAllTemperatureAsync();
        }

        void client_getAllTemperatureCompleted(object sender, getAllTemperatureCompletedEventArgs e)
        {
            int index = 0;
            DataSeries series = new DataSeries();
            series.Definition = new BarSeriesDefinition();
            series.LegendLabel = "溫度";
            if (e.Error == null)
            {
                System.Collections.ObjectModel.ObservableCollection<Temperature> trees = e.Result;
                foreach (Temperature item in trees)
                {
                    if (index < 20)
                    {
                        index++;
                        series.Add(new DataPoint(item.StationName, System.Convert.ToDouble(item.MaxTemp)));
                    }
                    else
                    {
                        break;
                    }
                }
            }
            radChart.DefaultView.ChartArea.DataSeries.Add(series);
        }

        private void chart_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            //string year = ((ComboBoxItem)chart.SelectedItem).Content.ToString();
            //setchart(year);
        }
    }
}

 

 

注意:這裡提供了全部核心程式碼,資料是通過WebService和資料庫互動獲取

原始碼下載連結:DCharting例項

 

 

相關文章