Selected Card via Picker is not displaying data

huangapple go评论59阅读模式
英文:

Selected Card via Picker is not displaying data

问题

Here is the translated code:

public partial class MenuPage : ContentPage, INotifyPropertyChanged
{
    // Transactions
    private ObservableCollection<TransactionData> _transactions = new ObservableCollection<TransactionData>();
    public ObservableCollection<TransactionData> Transactions
    {
        get { return _transactions; }
        set
        {
            _transactions = value;
            OnPropertyChanged(nameof(Transactions));
        }
    }

    // Cards
    private ObservableCollection<CardData> _cards = new ObservableCollection<CardData>();
    public ObservableCollection<CardData> Cards
    {
        get { return _cards; }
        set
        {
            _cards = value;
            OnPropertyChanged(nameof(Cards));
        }
    }
    // Selected Card
    private CardData _selectedCard;
    public CardData SelectedCard
    {
        get { return _selectedCard; }
        set { _selectedCard = value; OnPropertyChanged(nameof(SelectedCard)); OnPropertyChanged(nameof(IsCardSelected)); }
    }
    public bool IsCardSelected
    {
        get { return SelectedCard != null; }
    }

    // Active Account
    public Account SelectedAccount { get; }

    // Account Balance
    public class AccountBalance
    {

        [JsonProperty("status")]
        public string status { get; set; }

        [JsonProperty("msg")]
        public string msg { get; set; }

        [JsonProperty("data")]
        public string data { get; set; }
    }

    public MenuPage(Account _selectedAccount)
    {
        InitializeComponent();
        Title = "Transactions";
        BindingContext = this;
        SelectedAccount = _selectedAccount;
    }

    // When the screen appears
    protected override async void OnAppearing()
    {
        base.OnAppearing();
        await GetTransactionsAsync();
        await GetBalanceAsync();
        await GetCardsAsync();
    }

    // Confirm you want to go back
    protected override bool OnBackButtonPressed()
    {
        MainThread.BeginInvokeOnMainThread(async () =>
        {
            var result = await this.DisplayAlert("Alert!", "Do you really want to choose another account?", "Yes", "No");
            if (result) await this.Navigation.PopAsync();
        });

        return true;
    }

    // Get Transactions from Account
    private async Task GetTransactionsAsync()
    {
        string iban = App.ActiveAccount.iban;
        string url = "https://example";

        HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync(url);

        if (response.IsSuccessStatusCode)
        {
            string json = await response.Content.ReadAsStringAsync();
            TransactionsResponse responseObj = Newtonsoft.Json.JsonConvert.DeserializeObject<TransactionsResponse>(json);
            Transactions = responseObj.data;
        }
        else
        {
            Debug.WriteLine("Error: Unable to get transactions data.");
        }
    }

    // Get Account Balance
    private async Task GetBalanceAsync()
    {
        string iban = App.ActiveAccount.iban;
        string url = "https://example";

        HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync(url);
        var responseString = await response.Content.ReadAsStringAsync();

        if (response.IsSuccessStatusCode)
        {
            string json = await response.Content.ReadAsStringAsync();

            JObject resultX = JObject.Parse(responseString);
            JObject data = (JObject)resultX["data"];
            string account_balance = (string)data["account_balance"];
            balanceLabel.Text = account_balance + "€";

        }
        else
        {
            Debug.WriteLine("Error: Unable to get balance data.");
        }
    }

    // Get Client Cards

    private async Task GetCardsAsync()
    {
        int id_client = App.ActiveAccount.id_client_account;
        string url = "https://example";

        HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync(url);

        if (response.IsSuccessStatusCode)
        {
            string json = await response.Content.ReadAsStringAsync();
            CardsResponse responseObj = Newtonsoft.Json.JsonConvert.DeserializeObject<CardsResponse>(json);
            Cards = responseObj.data;
        }
        else
        {
            Debug.WriteLine("Error: Unable to get Card data.");
        }
    }


    // More Transactions -> Updates
    public new event PropertyChangedEventHandler PropertyChanged;

    protected override void OnPropertyChanged(string propertyName)
    {
        base.OnPropertyChanged(propertyName);

        if (propertyName == "Transactions")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Transactions"));
        }
        else
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public class TransactionsResponse
    {
        public ObservableCollection<TransactionData> data { get; set; }

    }

    public class CardsResponse
    {
        public ObservableCollection<CardData> data { get; set; }

    }
    private void GotoTransactionPage(object sender, EventArgs e)
    {
        Navigation.PushAsync(new MakeTransactionPage());
    }
    private void GotoLoanPage(object sender, EventArgs e)
    {
        Navigation.PushAsync(new LoansPage(SelectedAccount));
    }
}

Please note that the code you provided contains HTML-encoded characters (e.g., &quot;), which should be replaced with their actual characters (e.g., "). The code I provided assumes that these HTML-encoded characters have been corrected.

英文:

What I'm trying to do:
API retrieves an array of cards. However, only 1 is displayed. The user chooses whichever card he wants to use via a Picker. After selecting a card, the card data is displayed (Card Number, Valid Month and Year, etc.)

What is happening:
Picker is getting populated with the data from the API. After selecting a card, no data is displayed.

Things that I have checked:
Feedback is that the code is fine. Visual Studio is not reporting any data binding errors. Debugging runs fine, no exceptions, no nothing. API is running and data is being retrieved.

MenuPage.xaml

             xmlns:x=&quot;http://schemas.microsoft.com/winfx/2009/xaml&quot;
xmlns:local=&quot;clr-namespace:BankingApp&quot;
xmlns:res=&quot;clr-namespace:BankingApp.Resources&quot;
xmlns:toolkit=&quot;http://schemas.microsoft.com/dotnet/2022/maui/toolkit&quot;
x:Class=&quot;BankingApp.MenuPage&quot;
Title=&quot;MenuPage&quot;
BackgroundColor=&quot;#041014&quot;
Shell.NavBarIsVisible=&quot;False&quot; NavigationPage.HasBackButton=&quot;False&quot;&gt;
&lt;ScrollView&gt;
&lt;VerticalStackLayout&gt;
&lt;Label HorizontalOptions=&quot;Center&quot; Margin=&quot;0,20,0,20&quot; Text=&quot;{x:Static res:LanguageResources.YourAccount}&quot; FontSize=&quot;32&quot;/&gt;
&lt;!--Account Bank Card--&gt;    
&lt;Grid Margin=&quot;25,0,25,0&quot; &gt;
&lt;!--&lt;Image Source=&quot;bankcardesb.svg&quot; Aspect=&quot;AspectFill&quot;/&gt;--&gt;
&lt;StackLayout x:Name=&quot;selectedCardLayout&quot;
IsVisible=&quot;{Binding IsCardSelected}&quot;&gt;
&lt;Label Text=&quot;{Binding SelectedCard.card_number}&quot;
FontAttributes=&quot;Bold&quot;/&gt;
&lt;Label Text=&quot;{Binding SelectedCard.card_type}&quot; /&gt;
&lt;Label Text=&quot;{Binding SelectedCard.valid_month}&quot;/&gt;
&lt;/StackLayout&gt;
&lt;Frame&gt;
&lt;Label x:Name=&quot;balanceLabel&quot;  FontSize=&quot;Medium&quot; /&gt;
&lt;/Frame&gt;
&lt;/Grid&gt;
&lt;Picker x:Name=&quot;CardPicker&quot;
Margin=&quot;0,0,20,20&quot;
BackgroundColor=&quot;#5fb3f9&quot;
HorizontalTextAlignment=&quot;Center&quot;
HeightRequest=&quot;50&quot;
WidthRequest=&quot;150&quot;
HorizontalOptions=&quot;End&quot;
SelectedItem=&quot;{Binding SelectedCard}&quot;
ItemsSource=&quot;{Binding Cards}&quot;
SelectedIndex=&quot;0&quot;
ItemDisplayBinding=&quot;{Binding card_number}&quot; /&gt;
&lt;Button HorizontalOptions=&quot;Center&quot; Margin=&quot;10&quot; WidthRequest=&quot;200&quot; HeightRequest=&quot;50&quot; BackgroundColor=&quot;#00B2FF&quot;
Text=&quot;{x:Static res:LanguageResources.MakeTransaction}&quot; TextColor=&quot;White&quot; FontFamily=&quot;AgeoBold&quot; FontSize=&quot;18&quot; Clicked=&quot;GotoTransactionPage&quot;/&gt;
&lt;Button HorizontalOptions=&quot;Center&quot; Margin=&quot;10&quot; WidthRequest=&quot;200&quot; HeightRequest=&quot;50&quot; BackgroundColor=&quot;#00B2FF&quot;
Text=&quot;{x:Static res:LanguageResources.GoToLoans}&quot; TextColor=&quot;White&quot; FontFamily=&quot;AgeoBold&quot; FontSize=&quot;18&quot; Clicked=&quot;GotoLoanPage&quot;/&gt;
&lt;!--TransactionList--&gt;
&lt;StackLayout Margin=&quot;50,10,50,0&quot; VerticalOptions=&quot;EndAndExpand&quot; BindableLayout.ItemsSource=&quot;{Binding Transactions}&quot;&gt;
&lt;BindableLayout.ItemTemplate&gt;
&lt;DataTemplate&gt;
&lt;toolkit:Expander BackgroundColor=&quot;#5fb3f9&quot; Margin=&quot;0,0,0,5&quot; Padding=&quot;10&quot;&gt;
&lt;toolkit:Expander.Header&gt;
&lt;StackLayout Orientation=&quot;Horizontal&quot;&gt;
&lt;Label FontFamily=&quot;OpenSansSemibold&quot; Text=&quot;{Binding date_time}&quot; FontSize=&quot;Small&quot; HorizontalOptions=&quot;StartAndExpand&quot; /&gt;
&lt;Label FontFamily=&quot;OpenSansSemibold&quot; Text=&quot;{Binding amount}&quot; FontSize=&quot;Small&quot; HorizontalOptions=&quot;End&quot; /&gt;
&lt;Label FontFamily=&quot;OpenSansSemibold&quot; Text=&quot;{Binding currency}&quot; FontSize=&quot;Small&quot; HorizontalOptions=&quot;End&quot; /&gt;
&lt;/StackLayout&gt;
&lt;/toolkit:Expander.Header&gt;
&lt;StackLayout IsVisible=&quot;{Binding IsExpanded}&quot;&gt;
&lt;StackLayout Orientation=&quot;Horizontal&quot;&gt;
&lt;Label FontFamily=&quot;AgeoBold&quot; Text=&quot;{x:Static res:LanguageResources.RecipientName} &quot; FontSize=&quot;Small&quot; /&gt;
&lt;Label Text=&quot;{Binding name_recipient}&quot; FontSize=&quot;Small&quot; /&gt;
&lt;/StackLayout&gt;
&lt;StackLayout Orientation=&quot;Horizontal&quot; &gt;
&lt;Label FontFamily=&quot;AgeoBold&quot; Text=&quot;{x:Static res:LanguageResources.IBANPayer}&quot; FontSize=&quot;Small&quot; /&gt;
&lt;Label Text=&quot;{Binding iban_payer}&quot; FontSize=&quot;Small&quot; /&gt;
&lt;/StackLayout&gt;
&lt;StackLayout Orientation=&quot;Horizontal&quot; &gt;
&lt;Label FontFamily=&quot;AgeoBold&quot; Text=&quot;{x:Static res:LanguageResources.IBANRecipient}&quot; FontSize=&quot;Small&quot; /&gt;
&lt;Label Text=&quot;{Binding iban_recipient}&quot; FontSize=&quot;Small&quot; /&gt;
&lt;/StackLayout&gt;
&lt;StackLayout Orientation=&quot;Horizontal&quot;&gt;
&lt;Label FontFamily=&quot;AgeoBold&quot; Text=&quot;{x:Static res:LanguageResources.PaymentDescription}&quot; FontSize=&quot;Small&quot; /&gt;
&lt;Label Text=&quot;{Binding payment_description}&quot; FontSize=&quot;Small&quot; /&gt;
&lt;/StackLayout&gt;
&lt;StackLayout Orientation=&quot;Horizontal&quot; &gt;
&lt;Label FontFamily=&quot;AgeoBold&quot; Text=&quot;{x:Static res:LanguageResources.ReferenceNumber}&quot; FontSize=&quot;Small&quot; /&gt;
&lt;Label Text=&quot;{Binding reference_number}&quot; FontSize=&quot;Small&quot; /&gt;
&lt;/StackLayout&gt;
&lt;/StackLayout&gt;
&lt;/toolkit:Expander&gt;
&lt;/DataTemplate&gt;
&lt;/BindableLayout.ItemTemplate&gt;
&lt;/StackLayout&gt;
&lt;/VerticalStackLayout&gt;
&lt;/ScrollView&gt;
&lt;/ContentPage&gt;

MenuPage.xaml.cs

using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using BankingApp.Models;
using Microsoft.Maui.Controls;
using BankingApp.Services;
using Microsoft.Maui.Controls.Xaml;
using Newtonsoft.Json.Linq;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Xml;
using BankingApp.Views;
using Newtonsoft.Json;
using System.Runtime.CompilerServices;
namespace BankingApp
{
public partial class MenuPage : ContentPage, INotifyPropertyChanged
{
//Transactions
private ObservableCollection&lt;TransactionData&gt; _transactions = new ObservableCollection&lt;TransactionData&gt;();
public ObservableCollection&lt;TransactionData&gt; Transactions
{
get { return _transactions; }
set
{
_transactions = value;
OnPropertyChanged(nameof(Transactions));
}
}
//Cards
private ObservableCollection&lt;CardData&gt; _cards = new ObservableCollection&lt;CardData&gt;();
public ObservableCollection&lt;CardData&gt; Cards
{
get { return _cards; }
set
{
_cards = value;
OnPropertyChanged(nameof(Cards));
}
}
//Selected Card
private CardData _selectedCard;
public CardData SelectedCard
{
get { return _selectedCard; }
set { _selectedCard = value; OnPropertyChanged(nameof(SelectedCard)); OnPropertyChanged(nameof(IsCardSelected)); }
}
public bool IsCardSelected
{
get { return SelectedCard != null; }
}
//Active Account
public Account SelectedAccount { get; }
//Account Balance
public class AccountBalance
{
[JsonProperty(&quot;status&quot;)]
public string status { get; set; }
[JsonProperty(&quot;msg&quot;)]
public string msg { get; set; }
[JsonProperty(&quot;data&quot;)]
public string data { get; set; }
}
public MenuPage(Account _selectedAccount)
{
InitializeComponent();
Title = &quot;Transactions&quot;;
BindingContext = this;
SelectedAccount = _selectedAccount;
}
//When the screen appears
protected override async void OnAppearing()
{
base.OnAppearing();
await GetTransactionsAsync();
await GetBalanceAsync();
await GetCardsAsync();
}
//Confirm you want to go back
protected override bool OnBackButtonPressed()
{
MainThread.BeginInvokeOnMainThread(async () =&gt; {
var result = await this.DisplayAlert(&quot;Alert!&quot;, &quot;Do you really want to choose another account?&quot;, &quot;Yes&quot;, &quot;No&quot;);
if (result) await this.Navigation.PopAsync(); 
});
return true;
}
//Get Transactions from Account
private async Task GetTransactionsAsync()
{
string iban = App.ActiveAccount.iban;
string url = $&quot;https://example&quot;;
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
string json = await response.Content.ReadAsStringAsync();
TransactionsResponse responseObj = Newtonsoft.Json.JsonConvert.DeserializeObject&lt;TransactionsResponse&gt;(json);
Transactions = responseObj.data;
}
else
{
Debug.WriteLine(&quot;Error: Unable to get transactions data.&quot;);
}
}
//Get Account Balance
private async Task GetBalanceAsync()
{
string iban = App.ActiveAccount.iban;
string url = $&quot;https://example&quot;;
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(url);
var responseString = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
string json = await response.Content.ReadAsStringAsync();              
JObject resultX = JObject.Parse(responseString);
JObject data = (JObject)resultX[&quot;data&quot;];
string account_balance = (string)data[&quot;account_balance&quot;];
balanceLabel.Text = account_balance + &quot;€&quot;;
}
else
{
Debug.WriteLine(&quot;Error: Unable to get balance data.&quot;);
}
}
//Get Client Cards
private async Task GetCardsAsync()
{
int id_client = App.ActiveAccount.id_client_account;
string url = $&quot;https://example&quot;;
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
string json = await response.Content.ReadAsStringAsync();
CardsResponse responseObj = Newtonsoft.Json.JsonConvert.DeserializeObject&lt;CardsResponse&gt;(json);
Cards = responseObj.data;
}
else
{
Debug.WriteLine(&quot;Error: Unable to get Card data.&quot;);
}
}
//More Transactions -&gt; Updates
public new event PropertyChangedEventHandler PropertyChanged;
protected override void OnPropertyChanged(string propertyName)
{
base.OnPropertyChanged(propertyName);
if (propertyName == &quot;Transactions&quot;)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(&quot;Transactions&quot;));
}
else
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class TransactionsResponse
{
public ObservableCollection&lt;TransactionData&gt; data { get; set; }
}
public class CardsResponse
{
public ObservableCollection&lt;CardData&gt; data { get; set; }
}
private void GotoTransactionPage(object sender, EventArgs e)
{
Navigation.PushAsync(new MakeTransactionPage());
}
private void GotoLoanPage(object sender, EventArgs e)
{
Navigation.PushAsync(new LoansPage(SelectedAccount));
}
}
}

GetCards.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankingApp.Services
{
public class CardData
{
[JsonProperty(&quot;id_client_account&quot;)]
public string id_client_account { get; set; }
[JsonProperty(&quot;card_number&quot;)]
public string card_number { get; set; }
[JsonProperty(&quot;valid_month&quot;)]
public int valid_month { get; set; }
[JsonProperty(&quot;valid_year&quot;)]
public int valid_year { get; set; }
[JsonProperty(&quot;card_type&quot;)]
public string card_type { get; set; }
}
}

答案1

得分: 0

根据您提供的代码,Grid布局中,Frame包裹着StackLayout,所以您可能无法看到数据。您可以通过设置Grid布局中的RowDefinitionColumnDefinition来安排子元素,或者使用其他布局方式。

此外,目前Picker的SelectedIndex属性存在问题,您可以在代码中设置SelectedIndex,而不是在XAML中设置:

public MainPage()
{      
    InitializeComponent();
    ...
    CardPicker.SelectedIndex = 0;
}

更多信息,请参考Grid文档。希望对您有所帮助。

英文:
&lt;Grid Margin=&quot;25,0,25,0&quot; &gt;    
&lt;StackLayout x:Name=&quot;selectedCardLayout&quot;&gt;
&lt;Label Text=&quot;{Binding SelectedCard.card_number}&quot;&gt;
......
&lt;/StackLayout&gt;
&lt;Frame &gt;
&lt;Label x:Name=&quot;balanceLabel&quot;  FontSize=&quot;Medium&quot; /&gt;
&lt;/Frame&gt;
&lt;/Grid&gt;

According to your code above, in the Grid layout, the Frame shelters the StackLayout. So you cannot see the data. You could set the RowDefinition RowDefinition and ColumnDefinition to arrange the children in Grid layout or use other layout.

Also, there is an issue about SelectedIndex for Picker now : Picker SelectedIndex property not working. A workaround is to set SelectedIndex in the code behind instead of xaml:

public MainPage()
{      
InitializeComponent();
...
CardPicker.SelectedIndex = 0;
}

For more info, you could refer to Grid

Hope it works.

huangapple
  • 本文由 发表于 2023年5月8日 01:31:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76195358.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定