如何在Xamarin.Forms中将Label绑定到函数结果



我正在尝试将Label绑定到GetPlayCount()函数调用的结果。NameCategory的其他绑定按预期工作,但第三个标签没有输出

XAML:

<ListView ItemsSource="{Binding Games}"
HasUnevenRows="true" 
HeightRequest="200" 
SeparatorVisibility="Default">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<Grid Margin="0" Padding="0" RowSpacing="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Margin="0" Text="{Binding Name}"/>
<Label Grid.Column="1" Margin="0" Text="{Binding Category}"/>
<!--This following Label is the one not binding -->
<Label Grid.Column="2" Margin="0" Text="{Binding GetPlayCount}" />
</Grid>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

代码背后:

public partial class CollectionPage : ContentPage
{
CollectionViewModel collectionView = new CollectionViewModel();
public CollectionPage()
{
InitializeComponent();
BindingContext = collectionView;
}
}

ViewModel:

public class CollectionViewModel : INotifyPropertyChanged
{
private ObservableCollection<Game> games;
public ObservableCollection<Game> Games
{
get { return games; }
set
{
games = value;
OnPropertyChanged("Games");
}
}
public CollectionViewModel()
{
GetGames();
}

public async void GetGames()
{
var restService = new RestService();
Games = new ObservableCollection<Game>(await restService.GetGamesAsync());
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}

型号:

public class Game 
{
public string Name { get; set; }
public string Category { get; set; }
public async Task<int> GetPlayCount()
{
return (await new RestService().GetGamesAsync()).Where(result => result.Name == this.Name).Count();
}
}

您只能绑定到属性。您可以从属性getter调用该函数。但是,无法绑定到函数。应用程序不知道你的功能何时更新,所以绑定没有多大意义。对于该特性,可以调用PropertyChanged来表示该特性具有新值。

我将使用以下代码进行对话:

[NotMapped]
public decimal TotalPrice { get =>GetTotalPrice(); }
private decimal GetTotalPrice()
{
decimal result = 0;
foreach(var dpo in DetailPurchaseOrder)
{
result = result + dpo.GetTotalPurchasePrice();
}
return result;
}

最新更新