Xamarin Forms Bind label text to value of dictionary - c#

I have a problem. I am trying to bind my label to the value of my dictionary, so I would get a label foreach value in the dictionary. Now here is my code:
<ScrollView x:Name="categoryScrollView" HeightRequest="40" Orientation="Horizontal"
VerticalScrollBarVisibility="Never" HorizontalScrollBarVisibility="Never" HorizontalOptions="FillAndExpand">
<Frame CornerRadius="20" BackgroundColor="Black" BorderColor="DarkGray" HeightRequest="40">
<Label Text="{Binding categoryCollection[Value]}" FontSize="18" HorizontalTextAlignment="Center"
VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" TextColor="White" x:Name="txtCategory" />
</Frame>
</ScrollView>
And as you can see categoryCollection is my dictionary.
Here is the ViewModel:
private Dictionary<int, string> _categoryCollection;
public Dictionary<int, string> categoryCollection
{
get
{
return _categoryCollection;
}
set
{
if (_categoryCollection != value)
{
_categoryCollection = value;
OnPropertyChanged();
}
}
}
But after running the app, no text gets shown!?
What am I doing wrong?

so I would get a label foreach value in the dictionary.
Maybe you can use code to get each value from dictionary as follow :
Dictionary<int, string> dict = new Dictionary<int, string>(){{1,"One"},{2, "Two"},{3,"Three"}};
for (int i = 0; i < dict.Count; i++)
{
Console.WriteLine("Key: {0}, Value: {1}", dict.Keys.ElementAt(i), dict[ dict.Keys.ElementAt(i)]);
}
However this can not be displayed in Label or ScrollView dicrectly.
I suggest that using ListView to display loop list , ObservableCollection<Model> can be used as ItemSource for ListView .Then it will be easy displyed in each cell of listview .
You can create a Model class :
public class Employee
{
public int DisplayID {get; set;}
public string DisplayName {get; set;}
}
Then in ViewModel can set sample data :
ObservableCollection<Employee> employees = new ObservableCollection<Employee>();
public ObservableCollection<Employee> Employees { get { return employees; }}
public ViewModel()
{
// is set and the UI will react to changes
employees.Add(new Employee{ DisplayID = 1 , DisplayName="Rob Finnerty"});
employees.Add(new Employee{ DisplayID = 2 , DisplayName="Bill Wrestler"});
employees.Add(new Employee{ DisplayID = 3 , DisplayName="Dr. Geri-Beth Hooper"});
employees.Add(new Employee{ DisplayID = 4 , DisplayName="Dr. Keith Joyce-Purdy"});
employees.Add(new Employee{ DisplayID = 5 , DisplayName="Sheri Spruce"});
employees.Add(new Employee{ DisplayID = 6 , DisplayName="Burt Indybrick"});
}
Now in Xaml , add ListView in ContentPage :
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:constants="clr-namespace:XamarinFormsSample;assembly=XamarinFormsXamlSample"
x:Class="XamarinFormsXamlSample.Views.EmployeeListPage"
Title="Employee List">
<ListView x:Name="EmployeeView"
ItemsSource="{Binding Employees}">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding DisplayName}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage>
Not forget to bind ItemSource in ContenPage.cs :
public MainPage()
{
ViewModel viewmodel = new ViewModel();
EmployeeView.ItemsSource = viewmodel.employees ;
}
Here you can consider ViewModel as the Dictionary , employees contains the Key-Value data in each cell .In addition , you can add more property in Employee, then your cell will show much more styles.About custom data in listview , you can have a look at this doc to know more about it .
================================Update==================================
If need a horizonal listview , you can use CollectionView to implement it as follow :
<CollectionView ItemsSource="{Binding Monkeys}">
<CollectionView.ItemsLayout>
<LinearItemsLayout Orientation="Horizontal" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
...
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
There is a sample for reference .

Related

Maui Listview grouping

I have a list which consists of around 100 object. Each object has 2 properties (name, punch_time). The class is as follows:
public class Trxs
{
public string punch_time { get; set; }
public string name { get; set;}
}
the list name is (Punch_Times):
List<Trxs> Punch_times = new List<Trxs>();
It is a finger-print machine transactions. I want to populate a list view in Maui, so that the data will be grouped based on the name, as below:
It should show like this
I Tried the following grouping of the list, It showed the list grouped but without the group name. The listview name is (Trx_List):
var sorted = Punch_times.GroupBy(x => x.name)
.Select(grp => grp.ToList())
.ToList();
Trx_List.ItemsSource = sorted ;
the result showed like this (the group names are empty):
But it is showing like this
I have created a class to represent to new list, which will be the item source of the Trx_List as follows:
public class Grouped_list
{
public string emp_name { get; set; }
public List<Trxs> trxes { get; set; }
}
And created a new list:
List<Grouped_list> new_list = new List<Grouped_list>();
but how to copy the items from (sorted) to (new_list). Or is it needed? how to make item source of the list view grouped by name?
Any help please!
Thank you
To be frank, I recommend to use CollectionView instead of ListView. There is a known issue about iOS GroupHeaderTemplate :ListView GroupHeaderTemplate produces blank headers on iOS and MacCatalyst. It just render a blank headers. That's why i recommend to use CollectionView. The usage is almost the same. You could refer to Display grouped data in a CollectionView.
For your case, how to reflect sorted to new_list really matters. I made a small demo following the official documentation based on your code.
For MainPageViewModel.cs,
public class MainPageViewModel
{
public List<Trxs> Punch_times { get; set; } = new List<Trxs>();
public List<Grouped_list> new_list { get; set; } = new List<Grouped_list>();
public MainPageViewModel()
{
//Add some data for test
Punch_times.Add(new Trxs
{
name = "John",
punch_time = "13:33"
});
......
// translate list to dict (key is name)
var dict = Punch_times.GroupBy(o => o.name)
.ToDictionary(g => g.Key, g => g.ToList());
foreach (KeyValuePair<string, List<Trxs>> item in dict)
{
new_list.Add(new Grouped_list(item.Key,new List<Trxs>(item.Value)));
}
}
}
For Grouped_list.cs,
public class Grouped_list : List<Trxs>
{
public string Name { get; set; }
public Grouped_list(string name, List<Trxs> trxs) : base(trxs)
{
Name = name;
}
}
For MainPage.xaml which consumes the ListView or CollectionView,
<CollectionView ItemsSource="{Binding new_list}"
IsGrouped="True">
<CollectionView.GroupHeaderTemplate>
<DataTemplate>
<StackLayout>
<Label Text="{Binding Name}" TextColor="Black" VerticalOptions="CenterAndExpand"
BackgroundColor="LightGray"
FontSize="20"
FontAttributes="Bold" />
</StackLayout>
</DataTemplate>
</CollectionView.GroupHeaderTemplate>
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Label Text="{Binding punch_time}" BackgroundColor="Yellow"
FontSize="20" HorizontalTextAlignment="Center"
VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand"/>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
or you may use ListView but not render correctly on iOS as i mention above.
<ListView ItemsSource="{Binding new_list}"
IsGroupingEnabled="True">
<ListView.GroupHeaderTemplate>
<DataTemplate>
<ViewCell>
<Label Text="{Binding Name}" TextColor="Black" VerticalOptions="CenterAndExpand"
BackgroundColor="LightGray"
FontSize="20"
FontAttributes="Bold" />
</ViewCell>
</DataTemplate>
</ListView.GroupHeaderTemplate>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label Text="{Binding punch_time}" BackgroundColor="Yellow"
FontSize="20" HorizontalTextAlignment="Center"
VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
For more info, you could refer to ListView : Display grouped data and Display grouped data in a CollectionView
Hope it works for you.
public class Grouped_list : List<Trxs>
{
public string emp_name { get; set; }
public Grouped_list(string name, List<Trxs> list) : base(list)
{
emp_name = name;
}
}
You need something like that.
And then your observable is:
public ObservableCollection<Grouped_list> GroupedLists...
Set it as ItemSource, and don't forget to set IsGrouped to true.
In the GroupHeaderTemplate there should be binding to emp_name.
And its DataType should be Grouped_list.
Also, It is EmpName, not emp_name. And GroupedList not Grouped_list.
Follow the naming conventions.

Xamarin Android MVVM - Grouped CollectionView does not update UI after list changes

I have a grouped CollectionView with an ObservableCollection as ItemSource andthe list shows just fine,  with the itens grouped. The problem is that the UI does not get updated when i add or remove something from the collection. I need to pop and call the ProductsPage again to see the changes.
I even tried to refresh the entire list by calling the CreateGroups method after a change, it didn't work either.
Here´s parte of the code (i removed some unrelated code so there may be some inconsistencies)
ProdutosGroup
public class ProdutosGroup : ObservableCollection<Produto>
{
public string Titulo { get; set; }
public ProdutosGroup(string titulo, ObservableCollection<Produto> produtos) : base(produtos)
{
Titulo = titulo;
}
}
ProductsViewModel
public ObservableCollection<Produto> Produtos { get; set; } //the actual list of products
public ObservableCollection<ProdutosGroup> ProdutosAgrupadosList { get; set; }//the grouped list
public ListaDeProdutosViewModel(int idListaDeProdutos)
{
PopulateList();
CreateGroups();
}
public void CarregarProdutos()
{
this.Produtos = new ObservableCollection<Produto(App._produtoRepo.GetProdutos);
}
public void CreateGroups()
{
var idsCat = Produtos.Select(x => x.IdCategoria).Distinct();
var cats = new ObservableCollection<ProdutoCategoria>();
foreach (var idCat in idsCat)
{
cats.Add(App._categoriaRepo.GetProdutoCategoriaById(idCat));
}
foreach (var item in cats)
{
ObservableCollection<Produto> produtosDaCategoria = new ObservableCollection<Produto>();
foreach (var prod in Produtos)
{
if (prod.IdCategoria == item.Id)
produtosDaCategoria.Add(prod);
}
ProdutosAgrupadosList.Add(new ProdutosGroup(item.Descricao, new ObservableCollection<Produto>(produtosDaCategoria)));
}
}
ProductsPage
<ContentPage.Content>
<Grid>
<ScrollView >
<CollectionView ItemsSource="{Binding ProdutosAgrupadosList}" x:Name="Listas" IsGrouped="true">
<CollectionView.GroupHeaderTemplate>
<DataTemplate x:DataType="models:ProdutosGroup">
<Label Text="{Binding Titulo}" FontSize="28"/>
</DataTemplate>
</CollectionView.GroupHeaderTemplate>
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="models:Produto">
<Label VerticalTextAlignment="Center" Text="{Binding Nome}" FontSize="28"/>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</ScrollView>
<ImageButton Padding="12" Source="BasketPlus" Grid.Row="1" Command="{Binding AddForm}" HorizontalOptions="End" WidthRequest="68" HeightRequest="68" VerticalOptions="End" CornerRadius="100" Margin="0,0,16,22" BackgroundColor="{StaticResource Verde}"/>
</Grid>
</ContentPage.Content>
If you want to add an item in a group, you could simply use the following code:
ProdutosAgrupadosList[0].Add(
new Produto
{
Nome = "and"
}); // this will add the item at the end
or
ProdutosAgrupadosList[0].Insert(1,
new Produto
{
Nome = "and"
}); // add the item after the index1 item
To remove, you could either use ProdutosAgrupadosList[0].RemoveAt(index) or use a SwipeView which you could refer to CollectionView Context menus for more info. A simple demo using SwipeView like the following
<CollectionView.ItemTemplate>
<DataTemplate >
<SwipeView>
<SwipeView.LeftItems>
<SwipeItems>
<SwipeItem Text="Delete"
BackgroundColor="LightPink"
Command="{Binding Source={x:Reference Listas}, Path=BindingContext.DeleteCommand}"
CommandParameter="{Binding}" />
</SwipeItems>
</SwipeView.LeftItems>
<StackLayout>
<Label VerticalTextAlignment="Center" Text="{Binding Nome}" FontSize="28"/>
</StackLayout>
</SwipeView>
</DataTemplate>
</CollectionView.ItemTemplate>
That works for me based on the code in your question. For more info, you could refer to Xamarin.Forms CollectionView
Hope it works for you.

How can I toggle component in datatemplate, when I select an item?

I have a CollectionView in my page, which displays items. I need to toggle visual indicator (checkmark), that item is selected. The checkmark should be stylized, but I haven't done it, I only tried with BoxView. Nothing reasonable seems to work.
I have tried setting a flag in my Model if item is selected and then reload collection, but this is a very bad approach, that also consumes a lot of resources. I just need a toggle, that will appear on item click and dissappear on second one.
<Label Text="{Binding price, Converter={StaticResource Price}}" Style="{StaticResource PriceLabel}" Grid.Row="0" Grid.ColumnSpan="2"/>
<Label Text="{Binding name}" Style="{StaticResource CommonLabel}" VerticalTextAlignment="Center" Grid.Row="1" Grid.ColumnSpan="2"/>
<!-- Somehow change this-->
<BoxView BackgroundColor="Blue" Grid.Row="0" Grid.Column="1"/>
Disired result should look like this but that's another part of the story
According to your description, if you want to BoxView to display selected or unselected for Collectionview item, I suggest you can use one property to bind BoxView IsVisible, I do one sample that you can take a look:
Model:
public class Model:ViewModelBase
{
private string _DisplayName;
public string DisplayName
{
get { return _DisplayName; }
set
{
_DisplayName = value;
RaisePropertyChanged("DisplayName");
}
}
private bool _selected;
public bool Selected
{
get { return _selected; }
set
{
_selected = value;
RaisePropertyChanged("Selected");
}
}
}
ViewModel:
public class collectionviewmodel:ViewModelBase
{
public ObservableCollection<Model> Items { get; set; }
public collectionviewmodel()
{
Items = new ObservableCollection<Model>();
Items.Add(new Model() { DisplayName = "AAA", Selected = false });
Items.Add(new Model() { DisplayName = "BBB", Selected = false });
Items.Add(new Model() { DisplayName = "CCC", Selected = false });
Items.Add(new Model() { DisplayName = "DDD", Selected = false });
Items.Add(new Model() { DisplayName = "EEE", Selected = false });
}
}
ContentPage:
<CollectionView
x:Name="list1"
ItemsLayout="VerticalList"
ItemsSource="{Binding Items}"
SelectionChanged="List1_SelectionChanged"
SelectionMode="Single">
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout Orientation="Horizontal">
<Label
HorizontalOptions="StartAndExpand"
Text="{Binding DisplayName}"
TextColor="Fuchsia" />
<BoxView
HorizontalOptions="End"
IsVisible="{Binding Selected}"
Color="Fuchsia" />
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
public Page23 ()
{
InitializeComponent ();
this.BindingContext = new collectionviewmodel();
}
The screenshot like this:
What I did understand
you are trying to display an indicator on an item when it's selected, and only one item can be selected at the same time
So you need to set the SelectionMode to Single in your CollectionView, so only one item can be selected at a time
then you can display the indicator on the selected item and hide it on the previous one using OnCollectionViewSelectionChanged
you can find more details here Xamarin-Collectionview-Selection

ListView not deleting items in Xamarin.Forms. I have assigned an ObservableCollection to the ListView itemsource. MVVM

In my Xamarin.Forms app I have a simple Contact class [Model]. In the UI [View] there exists a ListView that displays the Contacts. In my model view class I have a list of Contacts (_listOfContacts) that is assigned to the itemSource property of the ListView. This list of Contacts is an ObservableCollection. My issue is the when user clicks Delete from ContextActions I can see that the _listOfContacts is updated but the ListView is not.
The ListView is only updated when I reassign its itemsource to the _listOfContacts. This should not be needed if _listOfContacts is an ObservableCollection of Contacts.
I am new to MVVM so I need to clear these basic MVVM concepts before I go on to learn more advanced techniques.
Here is my code:
Model
class Contact
{
public String Name { get; set; }
public String Status { get; set; }
public String ImageUrl { get; set; }
}
Model View
public partial class ContactListPage : ContentPage
{
private ObservableCollection<Contact> _listOfContacts;
public ContactListPage()
{
InitializeComponent();
_listOfContacts = new ObservableCollection<Contact>
{
new Contact {Name="Item1", ImageUrl="http://lorempixel.com/100/100/people/1" , Status="Hey"},
new Contact { Name = "Item2", ImageUrl = "http://lorempixel.com/100/100/people/2", Status="Hey" },
};
contactList.ItemsSource = _listOfContacts.ToList();
}
private void EditContactClick(object sender, EventArgs e)
{
DisplayAlert("Alert", "Clicked Edit", "Cancel");
}
private void DeleteContactClick(object sender, EventArgs e)
{
var contact = (sender as MenuItem).CommandParameter as Contact;
_listOfContacts.Remove(contact);
//following line of code should not be needed since _listOfContacts is
//an ObservableCollection and removing an item should update the bound control automatically
**contactList.ItemsSource = _listOfContacts.ToList();**
}
}
View
<ContentPage.Content>
<StackLayout>
<ListView x:Name="contactList" HasUnevenRows="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal" Padding="10">
<Image Source="{Binding ImageUrl}"/>
<StackLayout HorizontalOptions="StartAndExpand">
<Label Text="{Binding Name}" Margin="0,2,0,2"/>
<Label Text="{Binding Status}" Margin="0,2,0,2" />
</StackLayout>
</StackLayout>
<ViewCell.ContextActions>
<MenuItem Text="Edit" Clicked="EditContactClick" CommandParameter="{Binding .}"/>
<MenuItem Text="Delete" Clicked="DeleteContactClick" IsDestructive="True" CommandParameter="{Binding .}"/>
</ViewCell.ContextActions>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
I have tested your code, it is just the method ToList()which caused this question:
contactList.ItemsSource = _listOfContacts.ToList();
At the beginning, the type of _listOfContacts is ObservableCollection, but when you use the method ToList(),then it will been converted to List again.
So just delete the method 'ToList()', your code will work properly, just as follows:
contactList.ItemsSource = _listOfContacts;
Remove .toList() from contactList.ItemsSource = _listOfContacts.ToList(); and try again.
_listOfContacts is an ObservableCollection which should be used as your ItemsSource directly. Maybe go and check out the ObservableCollection documentation.

Picker not showing value in ContentView in ViewCell

This question is very similar to Picker not showing value in Xamarin.Forms on Windows Phone and UWP however there are some different aspects to this issue. Also the workaround selected as an answer to that question does not work in this case.
I have a ListView with an ItemTemplate that contains a ContentView. The ContentView contains a bindable picker. When the picker is selected the selected value is not displayed. This is an obvious bug because (1) you can resize the window and the value will appear and (2) this problem only occurs on UWP...iOS and Android versions are fine.
Here is the simplified issue. First the main window XAML...
<StackLayout Padding="10,40">
<Label>First List</Label>
<ListView Margin="20" x:Name="listView1" ItemsSource="{Binding ItemContexts}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<local:ContentView1
QuantityRows="{Binding Source={x:Reference listView1}, Path=BindingContext.QuantityRows}"
/>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Label>Second List</Label>
<ListView Margin="20" x:Name="listView2" ItemsSource="{Binding ItemContexts}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Picker x:Name="quantity" ItemsSource="{Binding Source={x:Reference listView2}, Path=BindingContext.QuantityView}" ItemDisplayBinding="{Binding FullName}"
SelectedItem="{Binding QuantityRow, Converter={StaticResource QuantityValueConverter}}"
WidthRequest="200">
</Picker>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Label>End</Label>
</StackLayout>
There are two list views. The second one works fine and the first one illustrates the problem.
Here is the XAML for the content view...
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="XamarinFormsBench.ContentView1" x:Name="contextView1">
<ContentView.Content>
<StackLayout Orientation="Horizontal">
<Picker x:Name="quantity" ItemsSource="{Binding Source={x:Reference contextView1}, Path=QuantityRows}" ItemDisplayBinding="{Binding Name}"
SelectedItem="{Binding QuantityRow}"
WidthRequest="200">
</Picker>
</StackLayout>
</ContentView.Content>
</ContentView>
Code behind for content view...
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ContentView1 : ContentView
{
public static BindableProperty QuantityRowsProperty = BindableProperty.Create("QuantityRows", typeof(ObservableCollection<QuantityRow>), typeof(SummaryDetailView), null, BindingMode.TwoWay, null);
public ObservableCollection<QuantityRow> QuantityRows
{
get
{
return GetValue(QuantityRowsProperty) as ObservableCollection<QuantityRow>;
}
set
{
SetValue(QuantityRowsProperty, value);
}
}
public ContentView1 ()
{
InitializeComponent ();
}
}
}
Finally here is the view model...
public class QuantityRow
{
public int ID { get; set; }
public string Name { get; set; }
}
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
QuantityRows = new ObservableCollection<QuantityRow>();
QuantityRows.Add(new QuantityRow() { ID = 1, Name = "Length" });
QuantityRows.Add(new QuantityRow() { ID = 2, Name = "Diameter" });
QuantityRows.Add(new QuantityRow() { ID = 3, Name = "Temperature" });
QuantityRows.Add(new QuantityRow() { ID = 4, Name = "Pressure" });
QuantityRows.Add(new QuantityRow() { ID = 5, Name = "Angle" });
}
public ObservableCollection<QuantityRow> QuantityRows { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
}
}
I am using Xamarin Forms 2.3.4.247 which is the last stable release as of this writing. I tried the latest pre-release which might fix the problem..it is impossible to say because it created a host of other issues.
I've tried invalidating the layout of the content view when the picker's selected index changes, but again, this seems to fix the one problem and create a host of other problems.
So it seems that this will be fixed in the next stable release of Xamarin Forms. What I need now is an effective workaround so I can work with what I have.
I have tested your code and reproduced your issue. The problem is that your BindingContext of ContentView1 has never been set value. And this design is inconsequent, although it can work in the ios and andriod. For your requirement, you could realize it via custom ViewCell.
<ViewCell xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="XamarinPickerTest.CustomViewCell">
<ViewCell.View>
<StackLayout>
<Picker x:Name="quantity" ItemsSource="{Binding QuantityRows}"
ItemDisplayBinding="{Binding Name}"
SelectedItem="{Binding SelectedQuantityRow}"
WidthRequest="200">
</Picker>
</StackLayout>
</ViewCell.View>
</ViewCell>
ViewModel.cs
public class ViewModel : ViewModelBase
{
public ViewModel()
{
QuantityRows = new ObservableCollection<QuantityRow>();
QuantityRows.Add(new QuantityRow() { ID = 1, Name = "Length" });
QuantityRows.Add(new QuantityRow() { ID = 2, Name = "Diameter" });
QuantityRows.Add(new QuantityRow() { ID = 3, Name = "Temperature" });
QuantityRows.Add(new QuantityRow() { ID = 4, Name = "Pressure" });
QuantityRows.Add(new QuantityRow() { ID = 5, Name = "Angle" });
}
private ObservableCollection<QuantityRow> quantityRows;
public ObservableCollection<QuantityRow> QuantityRows
{
get
{
return quantityRows;
}
set
{
quantityRows = value;
OnPropertyChanged();
}
}
private QuantityRow selectedQuantityRow;
public QuantityRow SelectedQuantityRow
{
get { return selectedQuantityRow; }
set
{
if (selectedQuantityRow != value)
{
selectedQuantityRow = value;
OnPropertyChanged();
}
}
}
}
public class QuantityRow : ViewModelBase
{
public int ID { get; set; }
public string Name { get; set; }
}
Usage
<ListView Margin="20" x:Name="listView1" ItemsSource="{Binding ItemContexts}" >
<ListView.ItemTemplate>
<DataTemplate>
<local:CustomViewCell/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
And the above solution works well in ios and android.

Categories