I need to develop a code displaying all Products along with their options so that they can be eventually checked with sliders for later price calculation.
What i want to achieve
The code for the MainPage with some dummy data for testing
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
List<Product> products = new List<Product>();
var stronaInternetowa = new Product("Webpage", 100f, new ProductOption("Option1", 10f));
var sklepInternetowy = new Product("Shop", 100f, new ProductOption("Option1", 10f));
products.Add(stronaInternetowa);
products.Add(sklepInternetowy);
listView.ItemsSource = products;
}
}
The ProductOption class for storing the data about the options for Product.
class ProductOption
{
public string OptionName { get; private set; }
public float OptionPrice { get; private set; }
public ProductOption(string name, float price)
{
OptionName = name;
OptionPrice = price;
}
}
XAML of MainPage with the ListView example of what i want to get
<ListView x:Name="listView" RowHeight="100">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label Text="{Binding Name}"></Label>
<!-- Here i would like to display all of the ProductOptions in the list along with Sliders -->
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
The Product class.
class Product
{
public string Name { get; set; }
public float Price { get; set; }
public List<ProductOption> ProductOptions { get; private set; } = new List<ProductOption>();
public Product(string name, float price,params ProductOption[] productOption)
{
Name = name;
Price = price;
foreach(ProductOption p in productOption)
{
ProductOptions.Add(p);
}
}
}
What I've tried so far:
Grouping, doesn't really work for me the way I tried to do it.
Nested ListView, but it isn't supported.
You can do some changes to enable the grouping:
XAML should be:
<ListView
x:Name="listView"
IsGroupingEnabled="True"
HasUnevenRows="True">
<ListView.GroupHeaderTemplate>
<DataTemplate>
<ViewCell Height="45">
<Grid Padding="10" BackgroundColor="WhiteSmoke">
<Label FontSize="18">
<Label.FormattedText>
<FormattedString>
<Span Text="{Binding Name}"/>
<Span Text=", "/>
<Span Text="{Binding Price}"/>
</FormattedString>
</Label.FormattedText>
</Label>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.GroupHeaderTemplate>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell Height="40">
<Grid Padding="10" BackgroundColor="White">
<Label FontSize="15">
<Label.FormattedText>
<FormattedString>
<Span Text="{Binding OptionName}"/>
<Span Text=", "/>
<Span Text="{Binding OptionPrice}"/>
</FormattedString>
</Label.FormattedText>
</Label>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Product model should be:
Make a note that I inherited the Product with List<ProductOptions>
public class Product : List<ProductOption>
{
public string Name { get; set; }
public float Price { get; set; }
public List<ProductOption> ProductOptions => this;
public Product(string name, float price, params ProductOption[] productOption)
{
Name = name;
Price = price;
foreach (ProductOption p in productOption)
{
ProductOptions.Add(p);
}
}
}
When I tried with following data:
var stronaInternetowa = new Product("Webpage", 100f, new ProductOption("Option1", 10f), new ProductOption("Option2", 20f), new ProductOption("Option3", 30f));
var sklepInternetowy = new Product("Shop", 100f, new ProductOption("Option1", 10f), new ProductOption("Option2", 20f));
I get the following result:
Related
I have a design with vertical and horizontal scrolling.I need to add two lists in to the same page.So I have used bindable layout for this but the scrolling is not working on this. Please help me on the below. I am stuck on this for a week.
Here is my View and ViewModel
<StackLayout BackgroundColor="WhiteSmoke">
<Grid ColumnDefinitions="*,*" RowDefinitions="Auto,*,Auto">
<StackLayout
Grid.Row="0"
Grid.Column="1"
BindableLayout.ItemsSource="{Binding ListSource.TestList2}"
Orientation="Horizontal"
VerticalOptions="FillAndExpand">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Label
Margin="0" WidthRequest="75"
FontSize="16"
HeightRequest="58"
HorizontalOptions="FillAndExpand"
MaxLines="3"
Text="{Binding Subname}"
VerticalOptions="FillAndExpand"
VerticalTextAlignment="Center" />
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
<StackLayout x:Name="layout1"
Grid.Row="1" Margin="30,0,0,0"
Grid.Column="0" Grid.ColumnSpan="2"
BindableLayout.ItemsSource="{Binding ListSource.TestList}"
Orientation="Vertical">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Grid ColumnDefinitions="*,*">
<Label
Grid.Column="0"
Margin="3"
Text="{Binding name}" />
<StackLayout
Grid.Column="1"
Margin="0"
BindableLayout.ItemsSource="{Binding classes}"
HorizontalOptions="FillAndExpand"
Orientation="Horizontal">
<BindableLayout.ItemTemplate>
<DataTemplate>
<StackLayout Orientation="Horizontal">
<RadioButton WidthRequest="75"
HorizontalOptions="FillAndExpand"
IsChecked="{Binding IsFailed}"/>
<Entry Placeholder="Subject"
IsVisible="{Binding IsEntry}"/>
</StackLayout>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
</Grid>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
</Grid>
</StackLayout>
ViewModel
public class ListViewVM:BaseViewModel
{
private TestClass _listSource;
public TestClass ListSource
{
get { return _listSource; }
set { _listSource = value;
OnPropertyChanged("ListSource");
}
}
//public
public ListViewVM()
{
TestClass kk=new TestClass();
kk.BindData();
ListSource = new TestClass();
ListSource.TestList =new List<TestName>(kk.TestList);
ListSource.TestList2= new List<TestSubject>( kk.TestList2);
ListSource.TestList.ForEach(x => x.classes=kk.TestList2);
var item = ListSource;
}}
Model
public class TestClass
{
public List<TestName> TestList { get; set; }
public List<TestSubject> TestList2 { get; set; }
public void BindData()
{
TestList = new List<TestName>() { new TestName {id=1,name="Jo"},
new TestName {id=2,name="Annie" },
new TestName {id=3,name="Alex" }};
TestList2 = new List<TestSubject>() { new TestSubject { id=1,Subname="Maths"},
new TestSubject { id=2,Subname="Physics"},
new TestSubject { id=2,Subname="Chemestry"},
new TestSubject { id=2,Subname="Other",IsEntry=true}};
}
}
public class TestName
{
public int id { get; set; }
public string name { get; set; }
public List<TestSubject> classes { get; set; }
}
public class TestSubject
{
public int id { get; set; }
public string Subname { get; set; }
public bool IsFailed {get;set;}
public bool IsOthersSelected { get; set; }
public bool IsEntry { get; set; }
}
Current UI
Some conditions is there , the user should select only one option from each row, but in my design they can select multiple option. If I add the RadioButton without that stacklayout the selection case is working but that time I cannot add the Entry field.If the user select "other" , then I need display an input field at the end along with "other" option for adding the other subject . So that field also mandatory for me.
I have a listview in xamarin and when i try to cast the selecteditem in a button clicked event it gives me the error. The class SavedVira is for a sqlite database table, i'm trying to use async but it seems to have been more trouble then worth. (i'm very new to programing). Here is my code:
XAML:
<ListView x:Name="SavedViraView" HasUnevenRows="True" ItemTapped="SavedViraView_ItemTapped">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<StackLayout Padding="10">
<Label Text="Navn:" FontSize="18" FontAttributes="Bold"/>
<Label Text="{Binding Virusnavn}" FontSize="15"/>
<Label Text="Symptomer:" FontSize="18" FontAttributes="Bold"/>
<Label Text="{Binding symptom1}"/>
<Label Text="{Binding symptom2}"/>
<Label Text="{Binding symptom3}"/>
<Label Text="{Binding symptom4}"/>
<Label Text="{Binding symptom5}"/>
<Label Text="{Binding symptom6}"/>
<Label Text="Lavet af:" FontSize="18" FontAttributes="Bold"/>
<Label Text="{Binding Creator}"/>
<Button Text="Load" x:Name="LoadButton" Clicked="LoadButton_Clicked"/>
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
XAML.CS:
private ObservableCollection<SavedVira> SavedVira = new ObservableCollection<SavedVira>();
public Ă…ben()
{
InitializeComponent();
}
protected override void OnAppearing()
{
nameLabel.Text = Values.currentUser;
Init();
}
private async void Init()
{
BindingContext = new SavedVira();
var Viralist = await DataServices.GetSavedVira();
SavedVira = new ObservableCollection<SavedVira>(Viralist);
SavedViraView.ItemsSource = SavedVira;
}
private void LoadButton_Clicked(object sender, EventArgs e)
{
var LoadVirus = ((ListView)sender).SelectedItem as SavedVira;
if (LoadVirus == null)
return;
Values.LoadBool = true;
Values.symptomZero = LoadVirus.symptom1;
Values.symptomOne = LoadVirus.symptom2;
Values.symptomTwo = LoadVirus.symptom3;
Values.symptomThree = LoadVirus.symptom4;
Values.symptomFour = LoadVirus.symptom5;
Values.symptomFive = LoadVirus.symptom6;
}
SavedVira cast/model:
[Table("savedvira")]
public class SavedVira
{
[PrimaryKey, AutoIncrement]
[Column("id")]
public int Id { get; set; }
[Column("virusnavn")]
public string Virusnavn { get; set; }
[Column("creator")]
public string Creator { get; set; }
[Column("symptoms1")]
public string symptom1 { get; set; }
[Column("symptoms2")]
public string symptom2 { get; set; }
[Column("symptoms3")]
public string symptom3 { get; set; }
[Column("symptoms4")]
public string symptom4 { get; set; }
[Column("symptoms5")]
public string symptom5 { get; set; }
[Column("symptoms6")]
public string symptom6 { get; set; }
}
Any help would be grealty appriciated!
the sender is a Button so this doesn't work
var LoadVirus = ((ListView)sender).SelectedItem as SavedVira;
instead do this
var btn = (Button)sender;
var selected = (SavedVira)btn.BindingContext;
also, using the same name for an instance variable and a class is confusing, I'd suggest you avoid it
SavedVira = new ObservableCollection<SavedVira>(Viralist);
I have 3 classes which are named Users, Cards, and BindingUser which is a class to bind them together.
public class User
{
public int Uid { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class CardData
{
public int _id { get; set; }
public string CardName { get; set; }
public string CardNote { get; set; }
}
public class BindingUser
{
public User bUser { get; set; }
public ObservableCollection<CardData> cardDatas { get; set; }
public BindingUser()
{
cardDatas = new ObservableCollection<CardData>();
}
}
I am trying to create a Horizontal stack layout, filled with frames for each user and in each frame is a list of cards belonging to that user.
I have tried doing this with listviews, stacklayouts and pretty much every other method google shows but each has the same result.
I get the frames for users, but they aren't populated.
My xaml looks like this, I know this is wrong but I formatted it like this to show what I am trying to achieve. In this example, the FirstName and LastName are working fine but the listviews aren't being populated.
<ContentPage.Content>
<StackLayout Orientation="Horizontal" BackgroundColor="#EBEBEB" HeightRequest="130" BindableLayout.ItemsSource="{Binding bindingUsers}" WidthRequest="410">
<BindableLayout.ItemTemplate>
<DataTemplate>
<StackLayout HeightRequest="300" VerticalOptions="Start" Orientation="Vertical">
<Frame CornerRadius="0"
HorizontalOptions="Start"
VerticalOptions="Start"
Margin="0"
Padding="0"
WidthRequest="410"
HeightRequest="80"
BackgroundColor="Red"
HasShadow="true">
<StackLayout Orientation="Vertical">
<Label Text="{Binding bUser.FirstName}"/>
<Label Text="{Binding bUser.LastName}"/>
</StackLayout>
</Frame>
<StackLayout Orientation="Vertical" BackgroundColor="Blue">
<ListView BindableLayout.ItemsSource="{Binding bindingUsers.cardDatas}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label Text ="{Binding CardName}"/>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</StackLayout>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
</ContentPage.Content>
Can someone point me in the right direction for what I am trying to achieve?
In .net forms it is such a simple task, and would take me minutes to do, but this has me beaten.
Here you have considered two things,
The first one, for listview, you have to use ItemsSource property instead of BindableLayout.ItemsSource.
The second one is the BindingContext of the template will be a single item of the bindable layout source. For example, in your case CardData. So the source, your trying to binding to the ListView is not a part of CardData. So when you bind different objects inside the data template, you have bound with BindingContext keyword like BindingContext.YourProperty with source reference. Refer to the below code,
<StackLayout x:Name="baseLayout" Orientation="Horizontal" BackgroundColor="#EBEBEB" HeightRequest="130"
BindableLayout.ItemsSource="{Binding cardDatas}" WidthRequest="410">
<BindableLayout.ItemTemplate>
<DataTemplate>
<StackLayout HeightRequest="300" VerticalOptions="Start" Orientation="Vertical">
<Frame CornerRadius="0"
HorizontalOptions="Start"
VerticalOptions="Start"
Margin="0"
Padding="0"
WidthRequest="410"
HeightRequest="80"
BackgroundColor="Red"
HasShadow="true">
<StackLayout Orientation="Vertical">
<Label Text="{Binding BindingContext.bUser.FirstName, Source={x:Reference baseLayout}}"/>
<Label Text="{Binding BindingContext.bUser.LastName, Source={x:Reference baseLayout}}"/>
</StackLayout>
</Frame>
<StackLayout Orientation="Vertical" BackgroundColor="Blue">
<ListView ItemsSource="{Binding BindingContext.cardDatas, Source={x:Reference baseLayout}}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label Text ="{Binding CardName}"/>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</StackLayout>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
And the model and view model class based on your codes,
public class User
{
public int Uid { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class CardData
{
public int _id { get; set; }
public string CardName { get; set; }
public string CardNote { get; set; }
}
public class BindingUser
{
public User bUser { get; set; }
public ObservableCollection<CardData> cardDatas { get; set; }
public BindingUser()
{
cardDatas = new ObservableCollection<CardData>()
{
new CardData()
{
_id = 1,
CardName = "Testing1",
CardNote = "Test data1",
},
new CardData()
{
_id = 2,
CardName = "Testing2",
CardNote = "Test data2",
},
new CardData()
{
_id = 3,
CardName = "Testing3",
CardNote = "Test data3",
},
};
bUser = new User
{
Uid = 23432,
FirstName = "First User",
LastName = "Last User",
};
}
}
It's better use the MVVM model if you're binding complex data, the view model helps you get a clearer picture of the view and model, I made some change to the code and hope it helps:
XAML:
<StackLayout BindableLayout.ItemsSource="{Binding Data}"
Orientation="Horizontal" BackgroundColor="#EBEBEB">
<BindableLayout.ItemTemplate>
<DataTemplate>
<StackLayout>
<Frame CornerRadius="0"
HorizontalOptions="Start"
VerticalOptions="Start"
Margin="0"
Padding="0"
WidthRequest="410"
BackgroundColor="Red"
HasShadow="true">
<StackLayout Orientation="Vertical">
<Label Text="{Binding FirstName}"/>
<Label Text="{Binding LastName}"/>
</StackLayout>
</Frame>
<ListView ItemsSource="{Binding cardDatas}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label Text ="{Binding CardName}"/>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
set BindingContext in MainPage:
public partial class MainPage : ContentPage
{
DemoViewModel viewModel = new DemoViewModel();
public MainPage()
{
InitializeComponent();
this.BindingContext = viewModel;
}
}
DemoViewModel:
class DemoViewModel
{
public ObservableCollection<BindingUser> Data { get; set; }
public DemoViewModel() {
Data = new ObservableCollection<BindingUser>
{
new BindingUser(1, "aa"),
new BindingUser(2, "bb"),
new BindingUser(3, "cc"),
new BindingUser(4, "dd")
};
}
}
Class User is deleted, CardData remains the same, also you can add it back if needed.
BindingUser:
class BindingUser
{
public int Uid { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ObservableCollection<CardData> cardDatas { get; set; }
public BindingUser(int uid, string name)
{
Uid = uid;
FirstName = name;
LastName = name;
cardDatas = new ObservableCollection<CardData>()
{
new CardData()
{
_id = 1,
CardName = "card 1",
},
new CardData()
{
_id = 2,
CardName = "card 2",
},
new CardData()
{
_id = 3,
CardName = "card 3",
},
};
}
}
I created a listview where it displays all categories based on the data from an API "cat_code", and if you tapped any of the it will transfer the value of the "cat_code" into a variable "selectedItem"
MenuCategories.xaml
<ListView x:Name="MyCategory" ItemSelected="MyCategory_ItemSelected" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell >
<StackLayout Orientation="Horizontal" HorizontalOptions="Center" VerticalOptions="Center" >
<Label Font="30" HorizontalTextAlignment="Center" x:Name="categoryname" Text="{Binding cat_code}"
Style="{DynamicResource ListItemTextStyle}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
MenuCategories.xaml.cs
private string selectedItem;
public MenuCategories()
{
InitializeComponent();
GetCategoryAsync();
}
public async Task GetCategoryAsync()
{
HttpClient client = new HttpClient();
var response = await client.GetStringAsync("http://ropenrom24-001-site1.etempurl.com/potangina/final/Restserver/index.php/category/view");
var cat = JsonConvert.DeserializeObject<List<Catergory>>(response);
MyCategory.ItemsSource = cat;
}
private void MyCategory_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var selectedCategory = e.SelectedItem as Catergory;
if (selectedCategory != null)
selectedItem = selectedCategory.cat_code;
DisplayAlert("Test", "Selected: " + selectedItem, "OK");
Catergory cat = new Catergory();
{
cat.cat_code = selectedItem;
}
var json = JsonConvert.SerializeObject(cat);
var content = new StringContent(json, Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
var result = await client.PostAsync("http://ropenrom24-001-site1.etempurl.com/potangina/final/Restserver/index.php/Products/view_cat", content);
}
If I post a cat_code:Asian it will display all of cat_code that has cat_code:Asian what I want to happen is how to get the underlined in this picture?
and transfer it to a viewmodel where i can display it to this listview?
MenuView.xaml
<ListView x:Name="ViewMenu">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Image Source="{Binding menu_image ,StringFormat='https://i.imgur.com/{0:F0}.png'}" Scale="1" />
<Label Text="{Binding menu_name}" Font="30"/>
<Label Text="{Binding menu_price,StringFormat=''}"/>
<Label Text="{Binding menu_availability} "/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Menus.cs
public class Menus
{
public string menu_code { get; set; }
public string cat_code { get; set; }
public string menu_name { get; set; }
public string menu_price { get; set; }
public string menu_description { get; set; }
public string menu_image { get; set; }
public string menu_inventory { get; set; }
public string menu_availability { get; set; }
}
Basically my question is how to get the json string underlined in the picture above?
try this.
string json_response = await result.Content.ReadAsStringAsync();
the json_response should contain the data you need.
I have one ListView on my page having ItemSource as List<AssetModel> as shown below:
public class AssetModel
{
public string AssetId { get; set; }
public string Description { get; set; }
public List<TaskDetail> TaskDetailList { get; set; }
}
public class TaskDetail
{
public string Description { get; set; }
}
How can I bind TaskDetail list in my parent list?
Desired Layout:
It seems like a classic grouping listview use case. James Montemagno wrote an article about this kind of need that should help you a lot.
In summary, the grouping feature expects an object of type 'List of List' (IEnumerable<IEnumerable<>>), where each 'master item' is a list of 'detail item'.
To make it easy, you can use the class provided at the above mentioned article:
public class Grouping<K, T> : ObservableCollection<T>
{
public K Key { get; private set; }
public Grouping(K key, IEnumerable<T> items)
{
Key = key;
foreach (var item in items)
this.Items.Add(item);
}
}
Then, the list property you must change its type to, for example, this:
ObservableCollection<Grouping<AssetModel, TaskDetail>> AssetsList { get; set; } =
new ObservableCollection<Grouping<AssetModel, TaskDetail>>();
This AssetsList is what you should bind to the ItemsSource of ListView
To fill this property, you'll need, for example, do this:
for (int i = 0; i < 5; i++)
{
var asset = new AssetModel();
asset.AssetId = new Guid().ToString();
asset.Description = $"Asset { i + 1} ";
asset.TaskDetailList = new List<TaskDetail>();
for (int j = 0; j < 3; j++)
asset.TaskDetailList.Add(new TaskDetail() { Description = $"Detail { (i + 1) } - { (j + 1) }" });
var group = new Grouping<AssetModel, TaskDetail>(asset, asset.TaskDetailList);
AssetsList.Add(group);
}
Then in your XAML you define your ListView Grouping properties:
<ListView ItemsSource="{Binding AssetsList}"
HasUnevenRows="True"
SeparatorVisibility="None"
SeparatorColor="Transparent"
IsGroupingEnabled="True">
<ListView.GroupHeaderTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<StackLayout Orientation="Horizontal">
<Label Text="AssetId"
FontAttributes="Bold"/>
<Label Text={Binding Key.AssetId}/>
</StackLayout>
<StackLayout Orientation="Horizontal">
<Label Text="Description"
FontAttributes="Bold"/>
<Label Text={Binding Key.Description}/>
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.GroupHeaderTemplate>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label Text={Binding Description}/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>