我复制了一个我发现的实现,它在 WPF Toolkit DataVisualization 的折线图上提供数据标签,并对其进行了一些更改。它显示数据点旁边的绘图值。图表会时不时地用不同的数据重新绘制自己,并且在发生这种情况时不会删除数据标签。
我覆盖RemoveDataPoint
了基类中的方法以尝试从中删除,TextBlock
但这Canvas
会抛出一个InvalidOperationException
(枚举器无效,因为集合已更改)。我了解为什么会发生异常,但是如何TextBlocks
从Canvas
相应的删除时DataPoint
删除?这是我到目前为止所拥有的:
public class DataTagLineSeries : LineSeries
{
private Canvas _labelsCanvas;
private readonly Dictionary<DataPoint, TextBlock> _currentLabels = new Dictionary<DataPoint, TextBlock>();
public bool DisplayLabels { get; set; }
public string LabelBindingPath { get; set; }
public Style LabelStyle { get; set; }
public Point LabelOffset { get; set; }
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
_labelsCanvas = (Canvas)GetTemplateChild("PlotArea");
Clip = null;
}
protected override void UpdateDataPoint(DataPoint dataPoint)
{
base.UpdateDataPoint(dataPoint);
if (DisplayLabels && dataPoint.Visibility == Visibility.Visible)
Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => CreateLabel(dataPoint)));
}
protected override void RemoveDataPoint(DataPoint dataPoint)
{
base.RemoveDataPoint(dataPoint);
if (_currentLabels.ContainsKey(dataPoint))
{
_labelsCanvas.Children.Remove(_currentLabels[dataPoint]);
_currentLabels.Remove(dataPoint);
}
}
private void CreateLabel(DataPoint dataPoint)
{
TextBlock label;
if (_currentLabels.ContainsKey(dataPoint))
{
label = _currentLabels[dataPoint];
}
else
{
label = new TextBlock();
_labelsCanvas.Children.Add(label);
_currentLabels.Add(dataPoint, label);
label.Style = LabelStyle;
var binding = LabelBindingPath != null
? new Binding(LabelBindingPath) { Source = dataPoint.DataContext }
: new Binding("DependentValue") { Source = dataPoint };
BindingOperations.SetBinding(label, TextBlock.TextProperty, binding);
}
var coordinateY = Canvas.GetTop(dataPoint) + LabelOffset.Y;
var coordinateX = Canvas.GetLeft(dataPoint) + LabelOffset.X;
Canvas.SetTop(label, coordinateY);
Canvas.SetLeft(label, coordinateX);
}
}