我使用System.Windows.Controls.DataVisualization.Charting
绘制并显示一个包含LineSeries的图表,其中Y值的范围介于1到5之间。我使用System.Collections.Generic.KeyValuePair(TKey,TValue)
向LineSeries添加值。我不想在Y标签图表中显示从1到5的数字,而是要显示从E到A的字母。
如何实现这一结果?
答案 0 :(得分:4)
首先创建一个转换器,将数值转换为字母值:
public class NumericToAlphaConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
switch (value.ToString())
{
case "1":
return "A";
case "2":
return "B";
case "3":
return "C";
case "4":
return "D";
case "5":
return "E";
default: return null;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
使用转换器定义自定义Y标签样式:
<Style TargetType="chartingToolkit:AxisLabel">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="chartingToolkit:AxisLabel">
<TextBlock DataContext="{TemplateBinding FormattedContent}" Text="{Binding Converter={StaticResource NumericToAlphaConverter}}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
这里是洞UI和背后的相应代码
<Window.Resources>
<wpfApplication12:NumericToAlphaConverter x:Key="NumericToAlphaConverter"/>
</Window.Resources>
<Grid>
<chartingToolkit:Chart Title="Line Series"
VerticalAlignment="Top" Margin="0" Height="254" >
<chartingToolkit:LineSeries x:Name="serie"
IndependentValueBinding="{Binding Path=Key}"
DependentValueBinding="{Binding Path=Value}"
IsSelectionEnabled="True"/>
<chartingToolkit:Chart.Axes>
<chartingToolkit:LinearAxis Orientation="Y"
Title="Y val"
Maximum="5"
Minimum="1"
>
<chartingToolkit:LinearAxis.AxisLabelStyle>
<Style TargetType="chartingToolkit:AxisLabel">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="chartingToolkit:AxisLabel">
<TextBlock DataContext="{TemplateBinding FormattedContent}" Text="{Binding Converter={StaticResource NumericToAlphaConverter}}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</chartingToolkit:LinearAxis.AxisLabelStyle>
</chartingToolkit:LinearAxis>
</chartingToolkit:Chart.Axes>
</chartingToolkit:Chart>
</Grid>
背后的代码:
public ObservableCollection<KeyValuePair<int, int>> LineSeriesData = new ObservableCollection<KeyValuePair<int, int>>()
{
new KeyValuePair<int, int>(12,1),
new KeyValuePair<int, int>(5,2),
new KeyValuePair<int, int>(5,3),
new KeyValuePair<int, int>(5,4)
};
public MainWindow()
{
InitializeComponent();
serie.ItemsSource = LineSeriesData;
}