C# Xamarin中如何将筛选后的Price列表绑定至Chart?
First, let's break down your setup: your LINQ query returns an IEnumerable<price[]> where each array is a group of price objects (matching your SelectedProduct name case-insensitively) sorted by TIMESTAMP. To bind this to a chart, we need to convert those string-based properties to chart-compatible types (DateTime for timestamps, numeric values for prices) and populate the chart's series.
Below’s a step-by-step implementation tailored for Windows Forms Chart (the most common .NET charting scenario), with explanations:
Step 1: Process Filtered Data & Populate the Chart
Your string TIMESTAMP and PRICE values need to be parsed to usable types first—charts can’t directly render string values for axes. Here’s how to handle that and build your chart:
// Your existing filtered data query var filteredProductGroups = from p in PriceList where p.NAME.Contains(SelectedProduct, StringComparison.OrdinalIgnoreCase) group p by p.NAME into grp select grp.OrderBy(a => a.TIMESTAMP).ToArray(); // Clear existing series to avoid duplicate data (optional but recommended) chart1.Series.Clear(); // Loop through each matching product group foreach (var productGroup in filteredProductGroups) { if (!productGroup.Any()) continue; // Skip empty groups to avoid errors // Create a new series for this product (uses the product name as the series label) var productSeries = new Series(productGroup.First().NAME) { ChartType = SeriesChartType.Line, // Swap with Column, Area, Bar, etc., as needed XValueType = ChartValueType.DateTime // Tell the chart our X-axis is DateTime values }; // Add each data point to the series foreach (var priceEntry in productGroup) { // Safely parse string values to valid types (prevents crashes from bad data) if (DateTime.TryParse(priceEntry.TIMESTAMP, out DateTime timestamp) && double.TryParse(priceEntry.PRICE, out double price)) { productSeries.Points.AddXY(timestamp, price); } else { // Log or handle invalid data (adjust based on your needs) Debug.WriteLine($"Skipping invalid entry: Timestamp={priceEntry.TIMESTAMP}, Price={priceEntry.PRICE}"); } } // Add the finished series to the chart chart1.Series.Add(productSeries); } // Optional: Tweak chart axes for better readability chart1.ChartAreas[0].AxisX.LabelStyle.Format = "yyyy-MM-dd HH:mm"; // Custom timestamp display format chart1.ChartAreas[0].AxisX.Title = "Timestamp"; chart1.ChartAreas[0].AxisY.Title = "Price";
Key Tips & Notes:
- Data Validation: Always use
TryParsefor string-to-type conversions—this avoids crashes if yourTIMESTAMPorPRICEfields have invalid values. - Multiple Series: Each matching product name gets its own series (e.g., if
SelectedProductis "Apple", you’ll get separate lines for "Apple Inc" and "Red Apple"). If you want all points in one series, skip grouping byNAMEor modify the loop to add all points to a single series. - Chart Type: Change
SeriesChartTypeto match your visualization needs (Line, Column, Area, etc.).
For WPF Toolkit Chart (if using WPF):
If you’re working with WPF, the approach uses data binding with a view model. First, create a class for chart points:
public class ChartDataPoint { public DateTime Timestamp { get; set; } public double Price { get; set; } public string ProductName { get; set; } }
Then convert your filtered data and bind it to the chart:
var chartData = new ObservableCollection<ChartDataPoint>(); foreach (var group in filteredProductGroups) { foreach (var entry in group) { if (DateTime.TryParse(entry.TIMESTAMP, out DateTime ts) && double.TryParse(entry.PRICE, out double p)) { chartData.Add(new ChartDataPoint { Timestamp = ts, Price = p, ProductName = entry.NAME }); } } } // Bind to your WPF chart (set DataContext) myWpfChart.DataContext = chartData;
In your XAML:
<charting:Chart Title="Product Price History"> <charting:LineSeries ItemsSource="{Binding}" DependentValuePath="Price" IndependentValuePath="Timestamp" Title="{Binding ProductName}"/> </charting:Chart>
Make sure you have the WPF Toolkit references added to your project for this to work.
内容的提问来源于stack exchange,提问作者user9198450

