C# WPF ItemsControl 循环绑定 LiveCharts 图表数据
在 WPF 中使用 ItemsControl 来循环绑定数据,并使用 LiveCharts 来绑定 X 和 Y 的点。
首先,你需要在你的 XAML 文件中创建一个 ItemsControl 来显示数据:
<ItemsControl ItemsSource="{Binding DataPoints}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding X}" />
<TextBlock Text="{Binding Y}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
然后,在你的 ViewModel 中创建一个名为 DataPoints 的可观察集合,用于存储 X 和 Y 的点:
public class ViewModel : INotifyPropertyChanged
{
private ObservableCollection<DataPoint> _dataPoints;
public ObservableCollection<DataPoint> DataPoints
{
get { return _dataPoints; }
set
{
_dataPoints = value;
OnPropertyChanged(nameof(DataPoints));
}
}
public ViewModel()
{
DataPoints = new ObservableCollection<DataPoint>();
// 添加一些点
DataPoints.Add(new DataPoint(1, 2));
DataPoints.Add(new DataPoint(3, 4));
DataPoints.Add(new DataPoint(5, 6));
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class DataPoint
{
public double X { get; set; }
public double Y { get; set; }
public DataPoint(double x, double y)
{
X = x;
Y = y;
}
}
最后,在你的 MainWindow 中设置 DataContext 为 ViewModel 的实例:
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
这样,你就可以在 ItemsControl 中循环绑定 DataPoints 中的点,并使用 LiveCharts 来显示 X 和 Y 的值。
原文地址: https://www.cveoy.top/t/topic/o5Id 著作权归作者所有。请勿转载和采集!