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

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; }
}

Related

how to create and display item.cs while the program is running?

I want to create items in a ListView to be displayed in a View, how do I go about doing this?
Code-Behinds and the other View's ViewModel, are basically empty, except for a Binding Context and a manually created item in the ViewModel for viewing and testing stuff.
I have been trying for a while and this is basically me admitting defeat, I am sorry for literally copy-pasting my code, but I am getting desperate, if you can, please do explain the solution and thank you very much
Model - Item.cs is
{
public string Name { get; set; }
public string Description { get; set; }
public string Image { get; set; }
public int Quantity { get; set; }
public string TypeOfQuantity { get; set; }
}
Xaml for creating items V
<StackLayout BackgroundColor="AliceBlue" Padding="10">
<Button Text="Button"
Command="{Binding ButtonCommand}"
Clicked="Mover_Clicked"/>
<Grid BackgroundColor="Black"
ColumnSpacing="3"
RowSpacing="3"
Padding="3"
HeightRequest="200">
<Entry Placeholder="Enter Name"
BackgroundColor="AliceBlue" VerticalTextAlignment="Center" HorizontalTextAlignment="Center" Text="{Binding NewItem.Name}" />
<Entry Placeholder="Enter Description"
Grid.Column="1" BackgroundColor="AliceBlue" VerticalTextAlignment="Center" HorizontalTextAlignment="Center" Text="{Binding NewItem.Description}"/>
<Entry Placeholder="Enter Quantity"
Grid.Row="1" BackgroundColor="AliceBlue" VerticalTextAlignment="Center" HorizontalTextAlignment="Center" Text="{Binding NewItem.Quantity}"/>
<Entry Placeholder="Enter Type of Quantity"
Grid.Row="1" Grid.Column="1" BackgroundColor="AliceBlue" VerticalTextAlignment="Center" HorizontalTextAlignment="Center" Text="{Binding NewItem.TypeOfQuantity}"/>
</Grid>
</StackLayout>
</ContentPage.Content>
Xaml for Displaying items V
<viewmodels:ViewModelBase/>
</ContentPage.BindingContext>
<ListView
BackgroundColor="Transparent"
ItemsSource="{Binding Items}"
HasUnevenRows="True"
SeparatorVisibility="None">
<ListView.ItemTemplate>
<DataTemplate x:DataType="model:Item">
<ViewCell>
<ViewCell.ContextActions>
<MenuItem Text="Delete" ></MenuItem>
<MenuItem Text="Edit" ></MenuItem>
</ViewCell.ContextActions>
<Grid Padding="20">
<Frame CornerRadius="15">
<StackLayout Orientation="Horizontal">
<Frame BackgroundColor="AliceBlue">
<Image HeightRequest="90"
Source="{Binding Image}"/>
</Frame>
<StackLayout>
<Label
WidthRequest="150"
Text="{Binding Description}"
FontSize="Large"
VerticalTextAlignment="Center"/>
<Label
WidthRequest="150"
Text="{Binding Name}"
FontSize="Large"
VerticalTextAlignment="Center"/>
<Grid HeightRequest="50" WidthRequest=" 170" Padding="10" VerticalOptions="Start">
<Label
Text="{Binding Quantity}"
HorizontalOptions="End"
FontSize="Large"/>
<Label
Text="{Binding TypeOfQuantity}"
FontSize="Large" Grid.Column="1"/>
<Button HeightRequest="25"
WidthRequest="25"
Text="+"
FontSize="Large" Grid.Column="2"
BackgroundColor="OrangeRed"/>
<Button HeightRequest="25"
Text="-"
FontSize="Large" Grid.Column="3"/>
</Grid>
</StackLayout>
</StackLayout>
</Frame>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.Header>
<Button x:Name="Mover" Clicked="Mover_Clicked" Text="Add new"></Button>
</ListView.Header>
</ListView>
</ContentPage>
ViewModelBase V
{
public ObservableRangeCollection<Item> Items { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Image { get; set; }
public int Quantity { get; set; }
public string TypeOfQuantity { get; set; }
public Item NewItem { get; set; }
public ViewModelBase()
{
Items = new ObservableRangeCollection<Item>();
}
}
ViewModel for item creation(which inherits ViewModelBase) V
{
public Command ButtonCommand { set; get; }
public ItemEntryPageViewModel()
{
ButtonCommand = new Command(AddItemCommand);
}
private void AddItemCommand(object obj)
{
Items.Add(NewItem);
}
} ```

How to get symbol and price to show individually in a listview on xamarin 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

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

BindingContext in MasterDetailPage

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;
}
}

How to access nested label via C#?

How to access ListViews item template element named TextButtonDetails to update its Text property?
i tried so -
TextButtonDetails.Text = AppResources.AppResources.MoreDetailsProduct;
and so
listView.FindByName<Label>("TextButtonDetails").Text = AppResources.AppResources.MoreDetailsProduct;
<ListView x:Name="listView" HorizontalOptions="FillAndExpand" HasUnevenRows="true" VerticalScrollBarVisibility="Default" Refreshing="Refresh" ItemSelected="Details">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Margin="20" VerticalOptions="StartAndExpand" Orientation="Vertical">
<Label Text="{Binding Title}" FontAttributes="Bold" VerticalTextAlignment="Start" HorizontalOptions="StartAndExpand" />
<Label Text="{Binding Text}" VerticalOptions="StartAndExpand" />
<Label VerticalTextAlignment="End" TextColor="#2196F3" x:Name="TextButtonDetails"></Label>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
You can set your resource value in your view model:
public class YourItemViewModel
{
public YourItemViewModel()
{
Title = ...
Text = ...
MoreDetailsLabel = AppResources.AppResources.MoreDetailsProduct;
}
public string Title { get; }
public string Text { get; }
public string MoreDetailsLabel { get; }
}
or use the TranslateExtension markup extension from the xamarin forms docs: https://learn.microsoft.com/en-US/xamarin/xamarin-forms/app-fundamentals/localization/text?tabs=windows#localizing-xaml
It's a good idea to support localization.
You will be able to reference your resource value directly like this:
<?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="UsingResxLocalization.FirstPageXaml"
xmlns:i18n="clr-namespace:UsingResxLocalization;assembly=UsingResxLocalization">
<StackLayout Padding="0, 20, 0, 0">
<Label Text="{i18n:Translate NotesLabel}" />
<Entry Placeholder="{i18n:Translate NotesPlaceholder}" />
<Button Text="{i18n:Translate AddButton}" />
</StackLayout>
</ContentPage>

Categories

Resources