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>
Related
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
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
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>
So, I have trouble binding data to my MasterDetailView. I'm getting no errors, and my code seems to be correct, based on sources that I have found online. However, nothing populates my MasterDetailView..
<MasterDetailPage.Master>
<ContentPage Title="Menu" BackgroundColor="#9BD2AD" x:Name="test">
<StackLayout Orientation="Vertical">
<Label Text="MENU" TextColor="#106073" HorizontalOptions="Center" FontAttributes="Bold" Margin="0,20,0,0" FontSize="Large"/>
<ListView ItemsSource="{Binding listOfItems}" x:Name="navigationDrawerList" RowHeight="55" SeparatorVisibility="None"> <!--ItemSelected="NavigationDrawerList_ItemSelected"-->
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout VerticalOptions="FillAndExpand" Orientation="Vertical" Padding="20,10,0,0">
<Label Text="{Binding Title}" TextColor="#106073" HorizontalTextAlignment="Start" FontSize="Medium"/>
<BoxView WidthRequest="2" HeightRequest="1" BackgroundColor="Beige"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage>
</MasterDetailPage.Master>
Cs
private List<MasterPageItem> listOfItems = new List<MasterPageItem>();
MasterPageItem pages = new MasterPageItem();
public SlideMenu()
{
InitializeComponent();
test.BindingContext = getPages();
}
public List<MasterPageItem> getPages()
{
listOfItems.Add(new MasterPageItem("TEST1", typeof(Test1)));
listOfItems.Add(new MasterPageItem("TEST2", typeof(Test2)));
return listOfItems;
}
MasterPageItem class
public class MasterPageItem
{
public string Title { get; set; }
public Type TargetType { get; set; }
public MasterPageItem()
{
}
public MasterPageItem(string Title, Type TargetType)
{
this.Title = Title;
this.TargetType = TargetType;
}
}
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.