How to get symbol and price to show individually in a listview on xamarin c# - c#

How to get symbol in one label and the price in another label in xamrain c#
What i need help on is how i can make the symbol and the price be together in a listview for all the different coins. You can see in the link under GetPrice different symbols and different prices. I just want to put them in groups and seperate them in a listview. Please help me.
This is my MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Crypto_Portfolio.MainPage">
<StackLayout>
<StackLayout Orientation="Horizontal" VerticalOptions="Start">
<ListView x:Name="priceList">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label Text="{Binding symbol}" />
<Label Text="{Binding price}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
<StackLayout Orientation="Horizontal" VerticalOptions="End">
<Button Clicked="priceClick" Text="Fetch Price" HorizontalOptions="CenterAndExpand" VerticalOptions="End"/>
</StackLayout>
</StackLayout>
</ContentPage>
This is my MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net.Http;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Xamarin.Forms;
namespace Crypto_Portfolio
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
GetPrice();
}
public class Crypto
{
public string symbol { get; set; }
public string price { get; set; }
}
private async void GetPrice()
{
HttpClient client = new HttpClient();
var response = await client.GetStringAsync("https://api.binance.com/api/v3/ticker/price");
var cryptoconverted = JsonConvert.DeserializeObject<List<Crypto>>(response);
priceList.ItemsSource = cryptoconverted;
}
void priceClick(object sender, EventArgs e)
{
GetPrice();
}
}
}

first, you need to deserialize the json from the webservice into a C# class. You can use json2csharp.com to to this
public class Stock
{
public string symbol { get; set; }
public string price { get; set; }
}
then in your GetPrice method
var response = await client.GetStringAsync("https://api.binance.com/api/v3/ticker/price");
var stocks = JsonConvert.DeserializeObject<List<Stock>>(response);
next, add a ListView to your XAML
<ListView x:Name="stockList">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label Text="{Binding symbol}" />
<Label Text="{Binding price}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
finally, assign your data to the ListView in GetPrice
stockList.ItemsSource = stocks

Related

How can I multi-select items in the model using picker in xamarin or otherwise?

xaml.cs page:
public partial class TalimatGorevEkle : ContentPage
{
TalimatGorevModelmobil Model;
public TalimatGorevEkle() {
InitializeComponent();
var kullanicilist = Methodlar.GorevliListeGetir(Sabitler.Token);
KullaniciSec.ItemsSource = kullanicilist.GorevliListe; //picker'da listelenecek kişiler
}
}
.xaml file:
<?xml version="1.0" encoding="UTF-8" ?>
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="OzelKalem.Views.ListeContentViews.TalimatGorevEkle">
<ContentPage.Content>
<ScrollView>
<StackLayout>
<Grid>
<StackLayout Grid.Row="0" Padding="8">
<Label Text="Görev Başlığı:" TextColor="#FF7F24" FontSize="14"></Label>
<Entry x:Name="talimatAdi" Placeholder="Görev Başlığı Giriniz" HeightRequest="60" ></Entry>
<Label Text="Görev Adı:" TextColor="#FF7F24" FontSize="14" ></Label>
<Entry x:Name="talimatGörevAdi" Placeholder="Görev Adı Giriniz" HeightRequest="60" ></Entry>
<Label Text= "Görevin Son Tarihini Seçiniz:" TextColor="#FF7F24" FontSize="14"></Label>
<DatePicker Format="dd-MM-yyyy HH:mm" x:Name="gorevSonTarih" TextColor="Black" ></DatePicker>
<Picker x:Name="KullaniciSec" Title="Kullanıcı seçiniz." ItemsSource="{Binding GorevliListeModel}" ItemDisplayBinding="{Binding GorevliKullaniciAdi}"></Picker>
<Button x:Name="SaveCourseButton" Clicked="GorevEkle" Command="{Binding}" Text="Kaydet" BackgroundColor="LightGray" TextColor="#FF7F24" Margin="3" />
</StackLayout>
</Grid>
</StackLayout>
</ScrollView>
</ContentPage.Content>
</ContentPage>
I have a list in xamarin I have it displayed in picker. But I want it to be multiple selectable. How can I write for it?
How should I select it as checkbox or over the picker?
Yes , for multi-select items, you can use
Multiple selection of CollectionView to achieve this.
And you can check the official sample here.
Of course, you can also add CheckBox to each item of the ListView to achieve this.
There is a similar thread here, you can check it here: How to create select all check box in xamarin form.
I have used collection view but I need to set the list of selected users to TaskList in my View model. Actually, I need to send all the data entered in this form to the Service using the View model.selected user
How can I assign a list to a variable?
TalimatGorevEkle.xaml.cs :
using System;
using System.Collections;
using System.Collections.Generic;
using OzelKalem.Models;
using Plugin.Toasts;
using Xamarin.Forms;
namespace OzelKalem.Views.ListeContentViews
{
public partial class TalimatGorevEkle : ContentPage
{
TalimatGorevModelmobil Model;
public TalimatGorevEkle() {
InitializeComponent();
var kullanicilist = Methodlar.GorevliListeGetir(Sabitler.Token);
CollectionView collectionView = new CollectionView
{
SelectionMode = SelectionMode.Multiple
};
collectionView.SetBinding(ItemsView.ItemsSourceProperty, "GorevliListeModel");
collectionView.SelectionChanged += OnCollectionViewSelectionChanged;
collectionlist.ItemsSource = kullanicilist.GorevliListe;
collectionlist.ScrollTo(kullanicilist.GorevliListe);
}
void OnCollectionViewSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var previous = e.PreviousSelection;
var current = e.CurrentSelection;
}
private void GorevEkle(object sender, EventArgs e)
{
var talimat = talimatAdi.Text;
var talimatGorev = talimatGörevAdi.Text;
var gorevSonTariih = gorevSonTarih.Date;
GorevliListeModel items = collectionlist.SelectedItems as GorevliListeModel;
}
}
}
TalimatGorevEkle.xaml:
<?xml version="1.0" encoding="UTF-8" ?>
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="OzelKalem.Views.ListeContentViews.TalimatGorevEkle">
<ContentPage.Content>
<ScrollView>
<StackLayout>
<Grid>
<StackLayout Grid.Row="0" Padding="8">
<Label Text="Görev Başlığı:" TextColor="#FF7F24" FontSize="14"></Label>
<Entry x:Name="talimatAdi" Placeholder="Görev Başlığı Giriniz" HeightRequest="60" ></Entry>
<Label Text="Görev Adı:" TextColor="#FF7F24" FontSize="14" ></Label>
<Entry x:Name="talimatGörevAdi" Placeholder="Görev Adı Giriniz" HeightRequest="60" ></Entry>
<Label Text= "Görevin Son Tarihini Seçiniz:" TextColor="#FF7F24" FontSize="14"></Label>
<DatePicker Format="dd-MM-yyyy HH:mm" x:Name="gorevSonTarih" TextColor="Black" ></DatePicker>
<!-- <Picker x:Name="KullaniciSec" Title="Kullanıcı seçiniz." ItemsSource="{Binding GorevliListeModel}" ItemDisplayBinding="{Binding GorevliKullaniciAdi}"></Picker>!-->
<Label Text="Kullanıcı Seçiniz:" TextColor="#FF7F24" FontSize="14" ></Label>
<CollectionView x:Name="collectionlist"
ItemsSource="{Binding GorevliListeModel}"
SelectionMode="Multiple"
SelectionChanged="OnCollectionViewSelectionChanged"
SelectedItems="{Binding GorevliKullaniciAdi}" Margin="10" HeightRequest="150">
<CollectionView.ItemTemplate >
<DataTemplate >
<StackLayout >
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="CommonStates">
<VisualState Name="Normal" >
<VisualState.Setters>
<Setter Property="BackgroundColor" Value="White" />
</VisualState.Setters>
</VisualState>
<VisualState Name="Selected">
<VisualState.Setters>
<Setter Property="BackgroundColor" Value="LightGray" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Label Text="{Binding GorevliKullaniciAdi}" FontSize="14" Padding="5"></Label>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
<Button x:Name="SaveCourseButton" Clicked="GorevEkle" Command="{Binding}" Text="Kaydet" BackgroundColor="LightGray" TextColor="#FF7F24" Margin="3" />
</StackLayout>
</Grid>
</StackLayout>
</ScrollView>
</ContentPage.Content>
</ContentPage>
Viewmodel:
public class TalimatGorevModelmobil
{
public string TalimatBaslik { get; set; }
public string TalimatGorevAdi { get; set; }
public int ID { get; set; }
public int TalimatID { get; set; }
public int Durum { get; set; }
public DateTime EklenmeTarihi { get; set; }
public int IslemKulID { get; set; }
public List<GorevliListeModel> GorevliListe { get; set; }
public DateTime SonTarih { get; set; }
public int ServisBaglantiDID { get; set; }
}
public class GorevliListeModel
{
public string GorevliKullaniciAdi { get; set; }
public string GorevliID { get; set; }
}

Contents of `Label` in `ListView` are not Showed

I would like to edit the MAUI initialized file to do the following
add an object to the BindingContext in MainPage.xaml.cs each time a Button is clicked
display the BindingContext using a ListView
In doing so, the above problem occurred. Specifically, the image below is what happened.
The code is as follows, we created Meeting.cs and AllMeetings.cs as Models.
MainPage.xaml.cs
namespace App.Views;
using App.Models;
public partial class MainPage : ContentPage
{
int count = 0;
public MainPage()
{
InitializeComponent();
BindingContext = new Models.AllMeetings();
}
private void OnCounterClicked(object sender, EventArgs e)
{
count++;
if (count == 1)
CounterBtn.Text = $"Clicked {count} time";
else
CounterBtn.Text = $"Clicked {count} times";
SemanticScreenReader.Announce(CounterBtn.Text);
((Models.AllMeetings)BindingContext).Add_Meeting(new Models.Meeting() { Name = "foo" });
}
}
MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:App.Views"
x:Class="App.Views.MainPage">
<ScrollView>
<VerticalStackLayout
Spacing="25"
Padding="30,0"
VerticalOptions="Center">
<Button
x:Name="CounterBtn"
Text="Click me"
SemanticProperties.Hint="Counts the number of times you click"
Clicked="OnCounterClicked"
HorizontalOptions="Center" />
<ListView ItemsSource="{Binding Meetings}" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label Text="{Binding Name}" />
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</VerticalStackLayout>
</ScrollView>
</ContentPage>
AllMeetings.cs
using System.Collections.ObjectModel;
namespace App.Models;
internal class AllMeetings
{
public ObservableCollection<Meeting> Meetings { get; set; } = new ObservableCollection<Meeting>();
public void Add_Meeting(Meeting meeting)
{
this.Meetings.Add(meeting);
}
}
Meeting.cs
namespace App.Models;
internal class Meeting
{
public string Name { get; set; };
}
When I wrote this code, no characters were output as shown in the above image, so the same thing happened when I changed the contents of ListView in MainPage.xaml as follows.
<ListView ItemsSource="{Binding Meetings}" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label Text="hoge" />
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

Problem with Xamarin app while calling an API

I'm a beginner with C# and whole .NET (just wanted to mention at the beginning). So I'm learning Xamarin and APIs.
I've got the problem with fetching some data from API (https://jsonplaceholder.typicode.com/posts) to display inside the app. Once I execute the app, it gives me an error:
System.InvalidCastException: 'Specified cast is not valid'.
I also don't see where is it failing (after error, exception window is blank - like not showing where it stops).
using ExerciseApp.Models;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Net.Http;
using Xamarin.Forms;
namespace ExerciseApp
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
GetPosts();
}
private async void GetPosts()
{
HttpClient client = new HttpClient();
var response = await client.GetStringAsync("https://jsonplaceholder.typicode.com/posts");
var posts = JsonConvert.DeserializeObject<List<Posts>>(response);
PostsListView.ItemsSource = posts;
}
}
}
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ExerciseApp.MainPage">
<StackLayout BackgroundColor="White">
<Frame BackgroundColor="#581845" Padding="10" CornerRadius="5" Margin="25">
<Label Text="ʕ•ᴥ•ʔ" HorizontalTextAlignment="Center" TextColor="White" FontSize="30"/>
</Frame>
<Label Text="Welcome to Exercise app with RESTAPI and NHibernate" TextColor="#581845" FontSize="Title" Padding="10" HorizontalTextAlignment="Center"/>
<Label FontSize="20" Padding="20" HorizontalTextAlignment="Center" TextColor="#581845">
<Label.FormattedText>
<FormattedString>
<FormattedString.Spans>
<Span Text="Here we will load some data"/>
</FormattedString.Spans>
</FormattedString>
</Label.FormattedText>
</Label>
<ListView x:Name="PostsListView">
<ListView.ItemTemplate>
<DataTemplate>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding id}" TextColor="#581845"></Label>
<Label Text="{Binding title}" TextColor="#581845"></Label>
</StackLayout>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage>
namespace ExerciseApp.Models
{
public class Posts
{
public int userId { get; set; }
public int id { get; set; }
public string title { get; set; }
public string body { get; set; }
}
}
ListView must use a Cell type in their template. Adding a ViewCell into your XAML will fix this problem
<ListView x:Name="PostsListView">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding id}" TextColor="#581845"></Label>
<Label Text="{Binding title}" TextColor="#581845"></Label>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
alternately, you can use a CollectionView which allows you to create templates without the restriction of using a Cell

Having trouble binding an Observable collection to my ListView in Xamarin Forms

I am very new to Xamarin Forms and I am trying to bind my Observable collection "DisplayItems" to my listview, but I cannot figure out how to do that and be able to display the name to the item. I can get the make listview.ItemsSource = DisplayItems, but when I do I don't know how to make the label in the listview display to get the name of the Item. Any help would be appreciated.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace ShoppingList
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Page1 : ContentPage
{
public ObservableCollection<Item> DisplayItems;
public Page1()
{
InitializeComponent();
DisplayItems = new ObservableCollection<Item>();
DisplayItems.Add(new Item("potato", 3.40, 3, false));
DisplayItems.Add(new Item("juice", 4.70, 5, true));
BindingContext = this;
}
}
}
XAML:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="ShoppingList.Page1"
Title ="ViewPage">
<ContentPage.Content>
<StackLayout>
<ListView x:Name="listview" ItemsSource="{Binding DisplayItems}" HasUnevenRows="True" HorizontalOptions="Fill" VerticalOptions="Fill" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell x:Name="viewcell">
<StackLayout>
<Label x:Name="ListCell" Text="{Binding name}"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
Having a look at this document about set model data for ListView. Data Binding in ListView.
You should define Item class as follow :
public class Item
{
public string name {get; set;}
}
Then in ContentPage add some data DisplayItems :
namespace ShoppingList
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Page1 : ContentPage
{
public ObservableCollection<Item> DisplayItems;
public Page1()
{
InitializeComponent();
DisplayItems = new ObservableCollection<Item>();
DisplayItems .Add(new Item{ name="Rob Finnerty"});
DisplayItems .Add(new Item{ name="Bill Wrestler"});
BindingContext = this;
}
}
}
Last in Xaml this can work:
<ListView x:Name="listview" ItemsSource="{Binding DisplayItems}" HasUnevenRows="True" HorizontalOptions="Fill" VerticalOptions="Fill" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell x:Name="viewcell">
<StackLayout>
<Label x:Name="ListCell" Text="{Binding name}"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

XAML ListView in Xamarin does not work

I started to learn Xamarin, and i am trying to create first test project. I created the ListView which displays the ObservableCollection from BindingContext. "Take" is a table that has three properties. The problem is, that when i run app on emulator the following eror dialog appears:"Process system isn't responding. Do you want to close it?"
But if i erase tag and all internal XAML code everything works well, but i want to dispalay values of properties of class "Take" in each element of ListView.
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="App1.Views.Page1">
<ContentPage.Content>
<StackLayout>
<Label Text="Welcome to my first project"></Label>
<Label Text="Why does it does not work?"></Label>
<ListView ItemsSource="{Binding GetList}">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Word}"></TextCell>
<Button Text="SomeText"></Button>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
And this is my C# BindingContext
public class SQLiteSamplePage
{
private readonly SQLiteConnection _sqLiteConnection;
private ObservableCollection<Take> list;
public SQLiteSamplePage()
{
_sqLiteConnection = DependencyService.Get<ISQLite>().GetConnection();
_sqLiteConnection.CreateTable<Take>();
_sqLiteConnection.Insert(new Take
{
Word = "SomeWord1",
Translation = "Some translation 1"
});
_sqLiteConnection.Insert(new Take
{
Word = "SomeWord",
Translation = "SomeTranslation"
});
list =new ObservableCollection<Take>( _sqLiteConnection.Table<Take>());
}
public ObservableCollection<Take> GetList
{
get { return list; }
}
}
And here is a code of a table
public class Table
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public string Word { get; set; }
public string Translation { get; set; }
}
Try to put the TextCell and the Button in a StackLayout or any kind of layout inside a <ViewCell> element:
<ListView ItemsSource="{Binding GetList}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<TextCell Text="{Binding Word}"></TextCell>
<Button Text="SomeText"></Button>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
The child of the DataTemplate element must be of or derive from type ViewCell.
You cannot combine a TextCell and something else, in your case a Button. If you want to show both Text and the Button you will need to use a custom cell.
This is done using the base class ViewCell and inside there you define the layout you want to show
<StackLayout>
<Label Text="Welcome to my first project"></Label>
<Label Text="Why does it does not work?"></Label>
<ListView ItemsSource="{Binding GetList}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label Text="{Binding Word}"></Label>
<Button Text="SomeText"></Button>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
Hope this helps.

Categories

Resources