如何在LiveCharts自定义ToolTip中移除值为NaN的系列?
解决LiveCharts自定义ToolTip过滤NaN数据点的问题
方案思路
由于TooltipData.Points是只读集合,无法直接修改或过滤,因此我们可以在自定义ToolTip内部创建一个过滤后的派生集合,将其作为UI绑定的数据源,而非直接使用原始的Data.Points。
修改C#代码
更新StockToolTip类,添加过滤后的属性并在Data更新时自动执行过滤逻辑:
using System.Collections.Generic; using System.Linq; using LiveCharts; using LiveCharts.Wpf; using System.ComponentModel; public partial class StockToolTip : IChartTooltip { private TooltipData _data; private IEnumerable<TooltipPoint> _filteredPoints; public StockToolTip() { InitializeComponent(); DataContext = this; } public event PropertyChangedEventHandler PropertyChanged; public TooltipData Data { get { return _data; } set { _data = value; // 过滤掉Y值为NaN的TooltipPoint FilteredPoints = _data?.Points.Where(p => !double.IsNaN(p.ChartPoint.Y)) ?? Enumerable.Empty<TooltipPoint>(); OnPropertyChanged(nameof(Data)); } } // 新增过滤后的集合属性,作为UI绑定源 public IEnumerable<TooltipPoint> FilteredPoints { get => _filteredPoints; private set { _filteredPoints = value; OnPropertyChanged(nameof(FilteredPoints)); } } public TooltipSelectionMode? SelectionMode { get; set; } protected virtual void OnPropertyChanged(string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
修改XAML代码
将ItemsControl的ItemsSource从Data.Points改为绑定到新增的FilteredPoints属性:
<UserControl x:Class="Stock_Software.StockToolTip" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="100" d:DesignWidth="200"> <Grid> <StackPanel> <ItemsControl ItemsSource="{Binding FilteredPoints}"> <ItemsControl.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Series.Title}" FontWeight="Bold" /> <TextBlock Text="{Binding ChartPoint.Y, StringFormat={}{0} SQM}" /> </StackPanel> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </StackPanel> </Grid> </UserControl>
说明
- 核心逻辑是在
Data属性更新时,通过Linq过滤掉ChartPoint.Y值为NaN的点,生成新的可枚举集合FilteredPoints - 该方案完全在自定义ToolTip内部处理,不会修改LiveCharts的原始只读数据,避免了权限问题
- 当
Data为null时,FilteredPoints会返回空集合,防止UI绑定报错
内容的提问来源于stack exchange,提问作者Kyle Efthimiou
相关产品推荐
相关产品推荐

