非MVVM模式下,如何在CollectionView填充后更新计算列值
无MVVM框架下更新CollectionView第三列内容的实现方案
1. 调整数据模型
新增PL属性用于存储计算结果,若要实现自动UI更新,可让模型实现INotifyPropertyChanged:
public class YourDataModel : INotifyPropertyChanged { // 原有属性(示例) public int Id { get; set; } private decimal _paid; public decimal Paid { get => _paid; set { _paid = value; OnPropertyChanged(nameof(Paid)); } } // 新增P/L计算结果属性 private decimal _pl; public decimal PL { get => _pl; set { _pl = value; OnPropertyChanged(nameof(PL)); } } // INotifyPropertyChanged实现 public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName)); } }
2. 编写XAML布局
将CollectionView第三列绑定到PL属性:
<!-- CollectionView控件 --> <CollectionView x:Name="tradeCollectionView"> <CollectionView.ItemTemplate> <DataTemplate> <Grid ColumnDefinitions="*,*,*"> <!-- 第一列:原有数据列(示例) --> <Label Grid.Column="0" Text="{Binding Id}" /> <!-- 第二列:Paid值 --> <Label Grid.Column="1" Text="{Binding Paid}" /> <!-- 第三列:计算后的P/L值 --> <Label Grid.Column="2" Text="{Binding PL}" /> </Grid> </DataTemplate> </CollectionView.ItemTemplate> </CollectionView> <!-- 外部价格标签 --> <Label x:Name="lblTicker" Text="0.0" />
3. CodeBehind逻辑实现
完成数据加载、计算更新及文本变化监听:
protected override void OnAppearing() { base.OnAppearing(); // 加载SQLite数据并初始化计算 LoadTradeData(); // 监听价格标签变化 lblTicker.TextChanged += LblTicker_TextChanged; } // 从SQLite加载数据并计算初始P/L private void LoadTradeData() { // 替换为你的SQLite查询逻辑 var tradeList = YourSQLiteHelper.GetAllTrades(); // 计算每行P/L UpdatePLValues(tradeList); // 绑定到CollectionView tradeCollectionView.ItemsSource = tradeList; } // 批量更新所有行的P/L值 private void UpdatePLValues(List<YourDataModel> tradeList) { if (!decimal.TryParse(lblTicker.Text, out decimal tickerValue)) return; foreach (var trade in tradeList) { trade.PL = trade.Paid - tickerValue; } } // 价格标签变化时重新计算并更新UI private void LblTicker_TextChanged(object sender, TextChangedEventArgs e) { if (tradeCollectionView.ItemsSource is List<YourDataModel> tradeList) { UpdatePLValues(tradeList); } } protected override void OnDisappearing() { base.OnDisappearing(); // 移除事件监听,避免内存泄漏 lblTicker.TextChanged -= LblTicker_TextChanged; }
说明
- 若不使用
INotifyPropertyChanged,修改PL后需重新赋值ItemsSource触发UI刷新:private void LblTicker_TextChanged(object sender, TextChangedEventArgs e) { if (tradeCollectionView.ItemsSource is List<YourDataModel> tradeList) { UpdatePLValues(tradeList); tradeCollectionView.ItemsSource = null; tradeCollectionView.ItemsSource = tradeList; } }
内容的提问来源于stack exchange,提问作者oshirowanen
相关产品推荐
相关产品推荐

