c# – 如何将图表的轴绑定到List()的特定索引?
我正在尝试使用
WPF工具包创建图表,其中Y轴正在通过List()中的值进行更新.我正在尝试通过特定索引访问该值.目前,绑定到List()的索引而不是int会创建“没有合适的轴可用于绘制依赖值”.例外.
这是我到目前为止所做的,请注意我尝试让DependentValuePath访问索引: <Charting:LineSeries VerticalAlignment="Stretch" HorizontalAlignment="Stretch" ItemsSource="{Binding Path=MemoryStats}" IndependentValuePath="Timestamp" DependentValuePath="ByteCount[0]" Title="Data Points"> 这是MemoryStats值在后面的代码中包含的内容: public List<int> ByteCount { get; set; } public DateTime Timestamp { get; set; } 当XAML中的LineSeries具有属性DependentValuePath =“ByteCount”并且代码隐藏使用简单的int时,该图表工作正常: public int ByteCount { get; set; } public DateTime Timestamp { get; set; } 如何将它绑定到List()的索引而不是int? 编辑 我已经能够通过命名其索引从后面的代码中获取列表中的特定值,但是在创建图表时将动态生成多个LineSeries.我想将每个绑定到List< int>()的索引,我每隔一秒左右重新创建一个. 这是MemoryStats用于更新UI的完整方法.它通过将所有LineSeries Y值更新为单个ByteCount int来工作,因此当前所有行看起来都相同. public class MemorySample { public static MemorySample Generate(List<int> dataPoints) { return new MemorySample { ByteCount = dataPoints[0],Timestamp = DateTime.Now }; } public int ByteCount { get; set; } public DateTime Timestamp { get; set; } } 当然,我希望所有的LineSeries都不同.我想让图表的每个LineSeries的X轴都是TimeStamp(因此它们都具有相同的TimeStamp),并且各种LineSeries的Y轴值由整数的List()更新,每个都使用单独的索引列表() 我会尝试实现一个类型转换器,但我不完全确定何时/何地这样做. 编辑2 我按照我想要的方式工作!我找到了很多帮助from this S.O. question regarding using multiple series in a line chart. 似乎类型转换器也可以正常工作,所以Shimrod已经回答了问题.但是,我最终做的是将LineSeries的ItemSource绑定到索引,然后检索该索引内容的数据. 那么,这就是LineSeries的样子: <Charting:LineSeries VerticalAlignment="Stretch" HorizontalAlignment="Stretch" ItemsSource="{Binding [0]}" IndependentValuePath="X" DependentValuePath="Y" Title="Data Points"> </Charting:LineSeries> 注意ItemSource绑定中的索引.在后面的代码中,我将控件的DataContext设置为ObservableCollection,它包含一个继承自’IList’的对象(您可以使用任何执行此操作的对象),并且该对象包含包含属性X和Y属性. public ObservableCollection<InheritsFromIList<ObjectWithXandYProperties>> VariableDataContextIsSetTo { get; set; } 访问ObservableCollection的特定索引将返回列表.然后,该列表中的项目显示在图表上. 解决方法
我认为最简单的方法是在类中添加一个属性,该属性是List的int值.
例如 int val { get { return ByteCount[0]; } } 或者您也可以创建一个转换器,它将列表作为绑定,索引作为参数,并返回所需的值. 例如(我没试过这个): public class ElementOfListConverter : IValueConverter { public object Convert(object value,Type targetType,object parameter,System.Globalization.CultureInfo culture) { if (value is IList && parameter is int) { var lst = value as IList; int pos = (int)parameter; if (lst.Count >= pos) { return lst[pos]; } } return null; } public object ConvertBack(object value,System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } 编辑 以下是使用转换器的步骤: >创建类(ElementOfListConverter),如前所示. <Window.Resources> <local:ElementOfListConverter x:Key="ElemOfList" /> </Window.Resources> >在绑定中,指定要使用的转换器(使用其键) 此方法的专业版是您可以直接在xaml中指定元素的索引.您还可以使用 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |