如何在填充CollectionView后向其添加计算值



我有以下CodeBehindXAML,我用来从SQLite表中获取所有数据并填充CollectionView:

cs

protected override void OnAppearing()
{
base.OnAppearing();
List<Record> records = App.RecordRepo.GetAllRecords();
recordList.ItemsSource = records;
}

.xaml

<Grid Grid.Row="0">
<VerticalStackLayout>
<Label x:Name="lblHoldingTotal" Text="Total"/>
<Label x:Name="lblAverageBuyPrice" Text="Average Buy Price"/>
<Label x:Name="lblTotalPaid" Text="Total Paid"/>
<Label x:Name="lblTicker" Text="Ticker"/>
<Label x:Name="lblHoldingValue" Text="Holding Value"/>
<Label x:Name="lblProfit" Text="Profit"/>
</VerticalStackLayout>
</Grid>
<Grid Grid.Row="1">
<CollectionView x:Name="recordList">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Text="{Binding Id}" />
<Label Grid.Column="1" Text="{Binding Amount}" />
<Label Grid.Column="2" Text="{Binding Paid}" />
<Label Grid.Column="3" Text="P/L" />
<Label Grid.Column="4" Text="{Binding PurchaseDate}" />
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</Grid>

我如何更新列3中的值(目前有P/L作为所有行的占位符)基于CollectionView的值在填充它之后,从Label以外的CollectionView的值,而不使用MVVM框架?

例如:

(Column 3 label text) = (Column 2 Label text value) - lblTicker.text

我们不能在Codebehind方式中更改Column3标签文本,因为它是在CollectionView的模板中设置的。我们也不能通过设置x:Name来访问codebehind中的标签到它。尝试使用数据绑定。您可以参考几个类似的情况:我如何访问特定的集合视图子视图?在本例中,标签"datacadastrolabel";和如何在Xamarin.Forms.

中为CollectionView/ListView中的控件设置x:Name

如何更新列3中的值

创建一个自定义类,用作ItemTemplate。

用法:

<CollectionView.ItemTemplate>
<DataTemplate>
<mynamespace:MyItemView ... />
</DataTemplate>
</CollectionView.ItemTemplate>

自定义类的XAML将类似于您现在在DataTemplate中所拥有的,但与任何其他XAML文件一样具有头文件:

<Grid xmlns="http://xamarin.com/schemas/2014/forms" 
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyNameSpace.MyItemView">
...
<... x:Name="someElement" ... />
</Grid>

在这个类中,当BindingContext被设置时,你可以做任何你需要做的事情:

public partial class MyItemView : Grid
{
...

protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
// The "model" that this row is bound to.
var item = (MyItemClass)BindingContext;
// The UI element you want to set dynamically.
someElement.SomeProperty = item....;
...
}
}

从CollectionView之外的Label中更新值

在页面后面的代码中,很容易设置属性值(不绑定到集合的项):

lblTicker.Text = "Whatever text is needed".

如果您需要更多内容,请添加"pseudo-code"(实际上不编译)的问题,这显示了你正在尝试做的一个例子。

最新更新