Im trying to bind my ListView to an observableCollection on my ViewModel. The other bindings on the same class are working but i dont see any data where my list is supposed to be.
Ive tried setting the rows uneven, instantiating a separate Collection, and using breakpoints to confirm there is data.
Here is the xaml code:
<StackLayout Spacing="10" Padding="7" Grid.Row="1" Grid.Column="0">
<Label Text="Name:" FontSize="Medium"/>
<Label Text="{Binding order.Name}" FontSize="Small"/>
<Label Text="Price:" FontSize="Medium"/>
<Label Text="{Binding order.Price}" FontSize="Small"/>
</StackLayout>
<ListView ItemsSource="{Binding order.foodItems}" Grid.Row="0" Grid.Column="0" HasUnevenRows="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Padding="10" Orientation="Horizontal" HorizontalOptions="Fill">
<Label Text="{Binding Name}" FontSize="Medium"/>
<Label Text="{Binding Quantity}" FontSize="Medium" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Here is my ViewModel
Order _order;
public Order order
{
get { return _order; }
set { SetProperty<Order>(ref _order, value); }
}
public OrderDetailViewModel(Order value)
{
order = value;
}
The order class:
public class Order
{
public string Name { get; set; }
public ObservableCollection<IFoodItems> foodItems;
public double Price { get; set; }
public Order(string name)
{
Name = name;
foodItems = new ObservableCollection<IFoodItems>();
}
public void SetPrice(double value)
{
Price = value;
}
public void AddItem(IFoodItems food)
{
foodItems.Add(food);
}
}
Related
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);
}
} ```
This sounds like a mouthful but I have a BindableLayout.ItemTemplateSelector that is located inside of a DataTemplate. The problem is I can not pass a property of the DataTemplate's ItemSource for some reason.
In section 'Data Template', of 'The Code' below, I am trying to access properties inside of ItemSource="{Binding CarouselItems}" from within <controls:ThoughtEntryDataTemplateSelector>. However, I can't access anything inside of there except for StaticResource's.
I'd like to pass a property from CarouselItems into it
The Code
Data Template
<cards:CarouselView
x:Name="ThoughtCarouselViewer"
IndicatorView="indicatorView"
IsCyclical="False"
ItemsSource="{Binding CarouselItems}">
<cards:CarouselView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Label
x:Name="Title"
FontAttributes="Bold"
Text="{Binding Header}"
TextColor="{StaticResource TextColor}" />
<rv:MaterialFrame
Padding="5"
LightThemeBackgroundColor="#F1F1F1"
Style="{StaticResource CardView}">
<StackLayout BindableLayout.ItemsSource="{Binding Source={RelativeSource AncestorType={x:Type local:ThoughtRecordViewModel}}, Path=ThoughtEntryContainers}" Orientation="Vertical">
<BindableLayout.ItemTemplateSelector>
<controls:ThoughtEntryDataTemplateSelector
ChallengingThought="{StaticResource ChallengingThought}"
Distortions="{StaticResource Distortions}"
NegativeThought="{StaticResource NegativeThought}"
ThoughtType="{Binding ThoughtEntryType}" /> <============================== What I am trying to access
</BindableLayout.ItemTemplateSelector>
</StackLayout>
</rv:MaterialFrame>
</StackLayout>
</DataTemplate>
</cards:CarouselView.ItemTemplate>
</cards:CarouselView>
DataTemplateSelector
public class ThoughtEntryDataTemplateSelector : DataTemplateSelector
{
public DataTemplate NegativeThought { get; set; }
public DataTemplate Distortions { get; set; }
public DataTemplate ChallengingThought { get; set; }
public ThoughtEntryType ThoughtType { get; set; }
protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
DataTemplate dataTemplate;
if(ThoughtType == ThoughtEntryType.NegativeThought)
{
dataTemplate = NegativeThought;
} else if(ThoughtType == ThoughtEntryType.Distortion)
{
dataTemplate = Distortions;
} else
{
dataTemplate = ChallengingThought;
}
return dataTemplate;
}
}
Carousel Items
public class ThoughtEntryCarouselItems
{
private string header;
public string Header
{
get => header;
set => header = value;
}
private ThoughtEntryType thoughtEntryType;
public ThoughtEntryType ThoughtEntryType
{
get => thoughtEntryType;
set => thoughtEntryType = value;
}
}
According to Creating a Xamarin.Forms DataTemplateSelector, I suggest you can choose a DataTemplate for CarouselView, not for StackLayout, then you can get current item ThoughtEntryType in OnSelectTemplate method, please see my code.
<ContentPage.Resources>
<DataTemplate x:Key="ChallengingThought">
<StackLayout >
<Label FontAttributes="Bold" Text="{Binding Header}" />
<Frame CornerRadius="30" BorderColor="Black" BackgroundColor="AliceBlue">
<StackLayout BindableLayout.ItemsSource="{Binding EntryContainers}" Orientation="Vertical">
<Label Text="{Binding .}" />
</StackLayout>
</Frame>
</StackLayout>
</DataTemplate>
<DataTemplate x:Key="NegativeThought" >
<StackLayout>
<Label FontAttributes="Bold" Text="{Binding Header}" />
<Frame CornerRadius="30" BorderColor="Black" BackgroundColor="DarkGray">
<StackLayout BindableLayout.ItemsSource="{Binding EntryContainers}" Orientation="Vertical">
<Label Text="{Binding .}" />
</StackLayout>
</Frame>
</StackLayout>
</DataTemplate>
<DataTemplate x:Key="Distortions">
<StackLayout >
<Label FontAttributes="Bold" Text="{Binding Header}" />
<Frame CornerRadius="30" BorderColor="Black" BackgroundColor="YellowGreen">
<StackLayout BindableLayout.ItemsSource="{Binding EntryContainers}" Orientation="Vertical">
<Label Text="{Binding .}" />
</StackLayout>
</Frame>
</StackLayout>
</DataTemplate>
<local:ThoughtEntryDataTemplateSelector x:Key="EntryDataTemplateSelector"
ChallengingThought="{StaticResource ChallengingThought}"
Distortions="{StaticResource Distortions}"
NegativeThought="{StaticResource NegativeThought}"/>
</ContentPage.Resources>
<ContentPage.Content>
<StackLayout>
<CarouselView
x:Name="ThoughtCarouselViewer"
ItemsSource="{Binding CarouselItems}" ItemTemplate="{StaticResource EntryDataTemplateSelector}">
</CarouselView>
</StackLayout>
</ContentPage.Content>
public partial class Page24 : ContentPage
{
public Page24()
{
InitializeComponent();
this.BindingContext = new ThoughtRecordViewModel();
}
}
public class ThoughtRecordViewModel
{
public ObservableCollection<ThoughtEntryCarouselItems> CarouselItems { get; set; }
public ThoughtRecordViewModel()
{
CarouselItems = new ObservableCollection<ThoughtEntryCarouselItems>()
{
new ThoughtEntryCarouselItems(){Header="header 1",EntryType=ThoughtEntryType.ChallengingThought,EntryContainers=new ObservableCollection<string>(){"1","2","3"}},
new ThoughtEntryCarouselItems(){Header="header 2",EntryType=ThoughtEntryType.Distortions,EntryContainers=new ObservableCollection<string>(){"a","b","c"}},
new ThoughtEntryCarouselItems(){Header="header 3",EntryType=ThoughtEntryType.NegativeThought,EntryContainers=new ObservableCollection<string>(){"11","22","33"}},
new ThoughtEntryCarouselItems(){Header="header 4",EntryType=ThoughtEntryType.ChallengingThought,EntryContainers=new ObservableCollection<string>(){"112","2222","3333"}},
};
}
}
public class ThoughtEntryCarouselItems
{
private string header;
public string Header
{
get => header;
set => header = value;
}
private ThoughtEntryType _EntryType;
public ThoughtEntryType EntryType
{
get => _EntryType;
set => _EntryType = value;
}
public ObservableCollection<string> EntryContainers { get; set; }
}
public enum ThoughtEntryType
{
NegativeThought, Distortions, ChallengingThought
}
public class ThoughtEntryDataTemplateSelector : DataTemplateSelector
{
public DataTemplate NegativeThought { get; set; }
public DataTemplate Distortions { get; set; }
public DataTemplate ChallengingThought { get; set; }
protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
DataTemplate dataTemplate=null;
ThoughtEntryCarouselItems carouseitem = (ThoughtEntryCarouselItems)item;
if (carouseitem.EntryType == ThoughtEntryType.NegativeThought)
{
dataTemplate = NegativeThought;
}
else if (carouseitem.EntryType == ThoughtEntryType.Distortions)
{
dataTemplate = Distortions;
}
else if(carouseitem.EntryType == ThoughtEntryType.ChallengingThought)
{
dataTemplate = ChallengingThought;
}
return dataTemplate;
}
}
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'm trying to bind a command to a button inside a listView, but without success. I follow all other answers posted here, like this one:
Xamarin Forms Button Command binding inside a ListView
The actual result is that nothing happens. A thing that i notice is that visual studio, when i type after x:Reference suggests me just GridWebcam, like if it doesn't see other reference elements. What can i do?
Here my code:
<ContentPage
...
x:Name="WebcamList">
<ContentPage.Resources>
...
<ContentPage.Content>
<ListView ItemsSource="{Binding ListOfWebcam}"
SeparatorVisibility="None"
CachingStrategy="RecycleElement"
RowHeight="250"
VerticalOptions="FillAndExpand"
x:Name="ListWebcam">
<ListView.Header>
<StackLayout x:Name="HeaderStackLayout"
Padding="5,25,0,30"
Orientation="Horizontal"
HorizontalOptions="FillAndExpand">
<Label x:Name="LabelHeader"
Text="Webcam:"
FontSize="Large"
FontAttributes="Bold"
TextColor="{x:Static statics:Palette.PrimaryColor}"
VerticalOptions="Center"
HorizontalOptions="Start" Margin="10,0,0,0"/>
</StackLayout>
</ListView.Header>
<ListView.ItemTemplate>
<DataTemplate>
<controls:ExtendedViewCell IsEnabled="False">
<controls:ExtendedViewCell.View>
<Grid x:Name="GridWebcam">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Frame Grid.Column="1"
Grid.RowSpan="2"
CornerRadius="20"
BackgroundColor="{x:Static statics:Palette.PrimaryColor}"
VerticalOptions="FillAndExpand"
HorizontalOptions="FillAndExpand"
HasShadow="True"
Margin="5,10">
<StackLayout>
<Label Text="{Binding t_str_vid,Converter={StaticResource WebcamNameConverter}}"
FontSize="Medium"
TextColor="White"
FontAttributes="Bold"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand">
</Label>
<Label TextColor="White"
FontSize="Medium"
Text="{Binding direzione,Converter={StaticResource DirectionToStringConverter}}"/>
<StackLayout Orientation="Horizontal">
<ffimageloading:CachedImage LoadingPlaceholder="Rolling.gif"
DownsampleToViewSize="False"
VerticalOptions="FillAndExpand"
HorizontalOptions="StartAndExpand"
Source="{Binding image1}"/>
<iconize:IconButton Text="fas-play-circle"
FontSize="50"
HorizontalOptions="EndAndExpand"
VerticalOptions="EndAndExpand"
TextColor="White"
Command="{Binding BindingContext.OpenVideoWebcamCommand, Source={x:Reference WebcamList}}"
CommandParameter="{Binding .}"
BackgroundColor="Transparent"/>
</StackLayout>
</StackLayout>
</Frame>
</Grid>
</controls:ExtendedViewCell.View>
</controls:ExtendedViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage.Content>
</ContentPage>
```
public class WebcamListViewModel : BaseViewModel
{
public ICommand OpenVideoWebcamCommand { set; get; }
private List<Webcam> _ListOfWebcam { get; set; }
public List<Webcam> ListOfWebcam
{
get { return _ListOfWebcam; }
set
{
_ListOfWebcam = value;
OnPropertyChanged();
}
}
private Task DownloadFramesTask;
CancellationTokenSource tokenSourceDownloadFrames = new CancellationTokenSource();
CancellationToken cancellationTokenDownloadFrames;
public WebcamListViewModel(INavigationService navigationService, IApiAutostradeManagerFactory apiAutostradeManagerFactory) : base(navigationService,apiAutostradeManagerFactory)
{
OpenVideoWebcamCommand = new Command<Webcam>(async (webcam) => {
await navigationService.NavigateAsync(Locator.WebcamVideoPopUpPage);
Messenger.Default.Send(new InfoWebcamVideoMessage(webcam.c_mpr, webcam.c_uuid, webcam.t_str_vid));
});
}
Well it could be related to this mysterious controls:ExtendedViewCell of yours :)
Also did you disable the ListView selection: <ListView ... SelectionMode="None" /> ?
As Roubachof said that I don't know if it is related to controls:ExtendedViewCell,please check if you have binding BindingContext, then you can take a look the following code:
<StackLayout>
<ListView x:Name="listview1" ItemsSource="{Binding persons}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding Id}" />
<Label Text="{Binding name}" />
<Button
Command="{Binding BindingContext.command, Source={x:Reference listview1}}"
CommandParameter="{Binding Id}"
Text="Delete item" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
public partial class Page1 : ContentPage
{
public ObservableCollection<person> persons { get; set; }
public RelayCommand1 command { get; set; }
public Page1 ()
{
InitializeComponent ();
persons = new ObservableCollection<person>();
for(int i =0;i<20;i++)
{
person p = new person()
{
Id = i,
name = "cherry" + i
};
persons.Add(p);
command = new RelayCommand1(obj => method1((int)obj));
}
this.BindingContext = this;
}
public void method1(int Id)
{
persons.RemoveAt(Id);
//IEnumerable<person> list = persons.Where(x => x.Id == Id);
//foreach (person m in list)
//{
//}
}
}
public class person
{
public int Id { get; set; }
public string name { get; set; }
}
I am using Xamarin.Forms.I want to remove the selected item in listview after clicking Remove button.
My xaml
<ListView x:Name="ProductsListView"
HasUnevenRows="True"
BackgroundColor="#ecf0f1"
SeparatorVisibility="None"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Margin="6,4,6,4"
BackgroundColor="White">
<StackLayout Orientation="Horizontal">
<Label Text="Item ID" Margin="25,10,4,4" FontSize="Small" TextColor="Black" />
<Label Text="{Binding retail_modified_item_id}" Margin="25,10,4,4" TextColor="Black" FontSize="12" />
</StackLayout>
<StackLayout Orientation="Horizontal">
<Label Text="Name" Margin="25,2,8,4" TextColor="Black" FontSize="Small" />
<Label Text="{Binding name}" Margin="32,1,8,4" TextColor="Black" FontSize="Small" />
<Switch IsToggled="false" Margin="210,2,2,2" Toggled="Switch_Toggled" />
</StackLayout>
<StackLayout Orientation="Horizontal">
<Label Text="OldPrice" Margin="25,2,8,4" TextColor="Black" FontSize="Small"/>
<Label Text="{Binding old_price}" Margin="32,1,8,4" TextColor="Black" FontSize="Small" />
</StackLayout>
<StackLayout Orientation="Horizontal">
<Label Text="NewPrice" Margin="25,2,8,4" TextColor="Black" FontSize="Small" />
<Label Text="{Binding new_price}" Margin="32,1,8,4" TextColor="Black" FontSize="Small" />
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
My cs code
private void reject(object sender, EventArgs args)
{
foreach (var v in ProductsListView.SelectedItems)
{
ProductsListView.ItemSelected.Remove(v);
}
DisplayAlert("Rejected","Request Rejected!!", "OK");
}
I am getting this error:
listview does not contain a definition for selecteditem, ItemSelected
You can try cast it to ProductListView,
var selectedItems = (ListView/* or ProductListView*/)sender; //-> you need casting to access it.
And you can change list view item source
public void reject(your_list_of_model_type your_list_of_model)
{
your_list_of_model.RemoveRange(selectedItems);
ProductListView.ItemSource = your_list_of_model;
}
Solution 2 :
Here is what you could do :
This be my model class :
public class Item
{
public string ItemName { get; set; }
public string ItemDetails { get; set; }
}
And in my XAML or you can write this in code as well, bind to the Command Parameter of your Item template :
<Button Text="Delete" CommandParameter="{Binding ItemName}" Clicked="DeleteClicked"></Button>
Full Item Template will be like below :
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding ItemName}" HorizontalOptions="StartAndExpand" FontSize="30"></Label>
<Button Text="Delete" CommandParameter="{Binding ItemName}" Clicked="DeleteClicked">
</Button>
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
And in you code file you can do this :
public void DeleteClicked(object sender, EventArgs e)
{
var item = (Xamarin.Forms.Button)sender;
Item listitem = (from itm in allItems
where itm.ItemName == item.CommandParameter.ToString()
select itm)
.FirstOrDefault<Item>();
allItems.Remove(listitem);
}
IMPORTANT : This would only delete the item from the bound collection. To delete it from the original list you need to use ObservableCollection
You can add all the toggled items to a list, suppose selectedItems. And when you click REJECT button, delete the selectedItems from the datasource of listview.
The full code is like this:
MainPage.xaml:
<StackLayout Orientation="Vertical">
<!-- Place new controls here -->
<Button Text="APPROVE"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand" />
<Button Text="REJECT"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand"
Clicked="reject"/>
<ListView x:Name="ProductsListView"
HasUnevenRows="True"
BackgroundColor="#ecf0f1"
SeparatorVisibility="None"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Vertical" Margin="6,4,6,4"
BackgroundColor="White">
<StackLayout Orientation="Horizontal">
<Label Text="{Binding name}" Margin="32,1,8,4" TextColor="Black" FontSize="Small" />
<Switch IsToggled="false" Margin="210,2,2,2" Toggled="Switch_Toggled" />
</StackLayout>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding retail_modified_item_id}" Margin="25,10,4,4" TextColor="Black" FontSize="12" />
</StackLayout>
<StackLayout Orientation="Horizontal">
<Label Text="OldPrice" Margin="25,2,8,4" TextColor="Black" FontSize="Small"/>
<Label Text="{Binding old_price}" Margin="32,1,8,4" TextColor="Black" FontSize="Small" />
</StackLayout>
<StackLayout Orientation="Horizontal">
<Label Text="NewPrice" Margin="25,2,8,4" TextColor="Black" FontSize="Small" />
<Label Text="{Binding new_price}" Margin="32,1,8,4" TextColor="Black" FontSize="Small" />
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
MainPage.xaml.cs:
public partial class MainPage : ContentPage
{
ObservableCollection<ItemModel> allItems = new ObservableCollection<ItemModel>();
List<ItemModel> selectedItems = new List<ItemModel>();
public MainPage()
{
InitializeComponent();
InitializeData();
ProductsListView.ItemsSource = allItems;
}
private void reject(object sender, EventArgs e)
{
foreach (var v in selectedItems)
{
allItems.Remove(v);
}
DisplayAlert("Rejected", "Request Rejected!!", "OK");
}
private void Switch_Toggled(object sender, ToggledEventArgs e)
{
var switch1 = (Switch)sender;
var item = (ItemModel)switch1.BindingContext;
var isSelected = !item.selected;
if (isSelected)
{
selectedItems.Add(item);
}
else
{
selectedItems.Remove(item);
}
}
private void InitializeData() {
allItems.Add(new ItemModel { name = "Onion Rings, Medium",
retail_modified_item_id = 1000630,
old_price = 1.29,
new_price = 9.45,
selected = false
});
allItems.Add(new ItemModel
{
name = "Hashbrowns",
retail_modified_item_id = 1000739,
old_price = 0.99,
new_price = 8.5,
selected = false
});
allItems.Add(new ItemModel
{
name = "Amstel Light, Single",
retail_modified_item_id = 1002038,
old_price = 3.5,
new_price = 18,
selected = false
});
}
}
ItemModel.cs:
class ItemModel
{
public string name { get; set; }
public int retail_modified_item_id { get; set; }
public double old_price { get; set; }
public double new_price { get; set; }
public bool selected { get; set; }
}