I'm creating an ListView App on Visual Studio 2017 Xamarin.forms which shows me a list of my debts. I have added a DisplayActionSheet from "Dispalying Pop-ups" Microsoft Xamarin website. How can I delete a ListView Item on tapped through DisplayActionSheet ?
My DisplayActionSheet look's like this:
private async void DebtsList_ItemTapped(object sender, ItemTappedEventArgs e)
{
var action = await DisplayActionSheet("Details", "Close", null, "Cash", "Delete","");
Debug.WriteLine("Action: " + action);
}
and here is my ListView that shows me all my Debts:
<ListView x:Name="DebtsList"
ItemsSource="{Binding DebtEntries}"
CachingStrategy="RecycleElement"
Grid.Row="7"
Grid.ColumnSpan="3"
Grid.RowSpan="15"
HasUnevenRows="True"
ItemTapped="DebtsList_ItemTapped">
<ListView.Header>
<Grid BackgroundColor="White" Margin="7">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Label Text="Name" FontSize="11" FontAttributes="Bold" TextColor="#4a4a4a" Grid.Row="0" Grid.Column="0" />
<Label Text="Usage" FontSize="11" FontAttributes="Bold" TextColor="#4a4a4a" Grid.Row="0" Grid.Column="1" />
<Label Text="Value" FontSize="11" FontAttributes="Bold" TextColor="#4a4a4a" Grid.Row="0" Grid.Column="2" HorizontalOptions="End"/>
</Grid>
</ListView.Header>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid BackgroundColor="White" Margin="7">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Text="{Binding Name}"
Grid.Row="0"
Grid.Column="0"
FontSize="10"
TextColor="#4a4a4a"/>
<Label Text="{Binding Usage}"
Grid.Row="0"
Grid.Column="1"
FontSize="10"
TextColor="#4a4a4a"/>
<Label Text="{Binding Value}"
Grid.Row="0"
Grid.Column="2"
FontSize="10"
TextColor="#F33E3E"
FontAttributes="Bold"
HorizontalOptions="End"/>
<Label Text="{Binding CreationDate}"
Grid.Row="1"
Grid.Column="0"
FontSize="10"
TextColor="#4a4a4a"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Solution:
private async void ListView_ItemTapped(object sender, ItemTappedEventArgs e)
{
string result= await DisplayActionSheet("Details", "Close", null, "Cash", "Delete", "");
if(result=="Delete")
{
int position = DebtsList.TemplatedItems.GetGlobalIndexOfItem(e.Item);
mySource.RemoveAt(position);
DebtsList.ItemsSource = mySource;
}
}
mySource is the ItemsSource of the DebtsList,like
public ObservableCollection<DebtEntries> mySource { get; set; }
. . .
mySource = new ObservableCollection<DebtEntries>();
mySource.Add(new DebtEntries { Name = "xxx", Usage="xxx",Value="xxx",CreationDate="xxx"});
//. . .
DebtsList.ItemsSource = mySource;
Related
I have a dynamic checkbox,
private async void GetOffices()
{
string url = $"{baseurl}/get-offices";
var response = await httpservices.SendGetRequest(url);
for (int i = 0; i < response.Count; i++)
{
Offices.Add(new Office() { id = (string)response[i]["id"], OfficeName = (string)response[i]["office_name"] });
}
}
And my XAML looks like this:
<CollectionView ItemsSource="{Binding Offices}">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="viewmodel:Office" >
<Grid Padding="5">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Frame Grid.ColumnSpan="2" Padding="15" BackgroundColor="LightBlue" x:Name="OfficeSelection" CornerRadius="0">
<Grid Grid.ColumnSpan="2" RowDefinitions="Auto,Auto" ColumnDefinitions="40,*">
<CheckBox Grid.Column="0" x:Name="{Binding OfficeName}" CheckedChanged="OnCheckBoxCheckedChanged"/>
<Label TextTransform="Uppercase" Padding="10" FontSize="Default" Text="{Binding OfficeName}" Grid.Column="1"></Label>
</Grid>
</Frame>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
And it will display like this:
What I want to do is, when I click the continue button, I can get all the checked checkboxes Name or value where in this case are: ADMISSION, CASHIER, PLENARY HALL and store it in array?
This is my button XAML:
<Button
Grid.Row="1"
Grid.Column="0"
Margin="5"
BorderWidth="0"
Command="{Binding GetSelectedOfficesCommand}"
CornerRadius="0"
Text="Continue" />
[RelayCommand]
public void GetSelectedOffices()
{
//CODe HERE
}
MAUI related MS Docs is quiet confusing for me. Anyone can give me a code snippet to solve this?
You should add a boolean property to the office view model and bind it to the checkbox IsChecked. Then in your GetSelectedOffices function you just filter by this property:
var selectedNames = Offices.Where(x => x.IsSelected).Select(x => x.OfficeName);
Hope everyone is well. I'm running into a UI problem with my cross platform app for xamarin.forms. Basically it shows different on ios when compared to android.
I have a function on the AdminPage that when button clicks opens the PopupView, the popUp will either contain details on the user, or the order, for this example we are using orderDetails
private void ShowUserDetails_Clicked(object Sender, EventArgs e)
{
Button button = (Button)Sender;
string UserId = button.CommandParameter.ToString();
PopupNavigation.Instance.PushAsync(new PopupView(-1, int.Parse(UserId)));
}
The problem lies in the UI of the popUp, if you notice the android phone on the left of the image below. It loads the way I want it to. Displaying lable for email | phone number, followed by listview of OrderDetails below. As you can see it looks fine on the android. The problem is on the ios. Where is the whitespace coming from at the top of the PopUpView?
If you take a close look at the PopUpView on the iphone 11, there is a scroll bar to the right of the popUp . It starts where the text starts, and I cant scroll any further up. Its almost as if there is an extra row placed before anything else. I have looked extensively through the code and can't figure it out. So I want to remove the whitespace, have even tried listview.scrollTo for the listview but with no success..any help would be great thank you
<?xml version="1.0" encoding="utf-8" ?>
<pages:PopupPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="BottleShop.Views.PopupView"
xmlns:pages="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup"
xmlns:converters="clr-namespace:BottleShop.ViewModels.Converters">
<StackLayout x:Name="StackSearchResultsOuter" BackgroundColor="Transparent" HorizontalOptions="Center" VerticalOptions="Center">
<StackLayout.Resources>
<converters:ProductIdToProductNameConverter x:Key="converter"/>
</StackLayout.Resources>
<BoxView x:Name="InvisibleSpacer" BackgroundColor = "Transparent"
HeightRequest="80" />
<StackLayout x:Name="StackLayoutOrders" IsVisible="{Binding SLOrders}">
<ListView BackgroundColor="White" ItemsSource="{Binding PreviousOrderDetailsForUserLV}" HasUnevenRows="True" SeparatorVisibility="None">
<ListView.Header>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="30*" />
<ColumnDefinition Width="25*" />
<ColumnDefinition Width="25*" />
<ColumnDefinition Width="20*" />
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Grid.ColumnSpan="4" Grid.Row="0" x:Name="UserInfoLabel" HorizontalOptions="Center" Margin="10,10,0,0"/>
<BoxView Grid.Row="1"
Grid.ColumnSpan="4"
BackgroundColor="LightGray"/>
<Label Grid.Column="0" Text="Product" Grid.Row="1" HorizontalOptions="Center" Margin="0,10,0,0"/>
<Label Grid.Column="1" Grid.Row="1" Text="Quantity" HorizontalOptions="Center" Margin="0,10,0,0"/>
<Label Grid.Column="2" Grid.Row="1" Text="Price" HorizontalOptions="Center" Margin="0,10,0,0"/>
<Label Grid.Column="3" Grid.Row="1" Text="Sub" HorizontalOptions="Center" Margin="0,10,0,0"/>
<!--<BoxView Grid.Row="1"
Grid.ColumnSpan="4"
HeightRequest="1"
BackgroundColor="LightGray"/> -->
</Grid>
</ListView.Header>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid Padding="10" RowSpacing="10" ColumnSpacing="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="43*" />
<ColumnDefinition Width="8*" />
<ColumnDefinition Width="25*" />
<ColumnDefinition Width="24*" />
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Grid.Row="0" HorizontalOptions="StartAndExpand" VerticalOptions="StartAndExpand" Text="{Binding ProductId, Converter={StaticResource converter}}"/>
<Label Grid.Column="1" Grid.Row="0" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" Text="{Binding Quantity}"/>
<Label Grid.Column="2" Grid.Row="0" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" Text="{Binding PriceOfItem, StringFormat='£{0:0.00}'}"/>
<Label Grid.Column="3" Grid.Row="0" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" Text="{Binding SubtotalForThisItem, StringFormat='£{0:0.00}'}"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
<StackLayout x:Name="StackLayoutUsers" IsVisible="{Binding SLUsers}">
<ListView x:Name="UsersListView" BackgroundColor="White" ItemsSource="{Binding AllExistingUsersLV}" HasUnevenRows="True" SeparatorVisibility="None">
<ListView.Header>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="30*" />
<ColumnDefinition Width="25*" />
<ColumnDefinition Width="25*" />
<ColumnDefinition Width="20*" />
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Text="Address Line 1" Grid.Row="0" HorizontalOptions="Center" Margin="0,10,0,0"/>
<Label Grid.Column="1" Grid.Row="0" Text="Line 2" HorizontalOptions="Center" Margin="0,10,0,0"/>
<Label Grid.Column="2" Grid.Row="0" Text="Town" HorizontalOptions="Center" Margin="0,10,0,0"/>
<Label Grid.Column="3" Grid.Row="0" Text="Mobile" HorizontalOptions="Center" Margin="0,10,0,0"/>
<BoxView Grid.Row="1"
Grid.ColumnSpan="4"
HeightRequest="1"
BackgroundColor="LightGray"/>
</Grid>
</ListView.Header>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid Padding="10" RowSpacing="10" ColumnSpacing="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="43*" />
<ColumnDefinition Width="8*" />
<ColumnDefinition Width="25*" />
<ColumnDefinition Width="24*" />
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Grid.Row="0" HorizontalOptions="StartAndExpand" VerticalOptions="EndAndExpand" Text="{Binding AddressLine1}"/>
<Label Grid.Column="1" Grid.Row="0" HorizontalOptions="StartAndExpand" VerticalOptions="EndAndExpand" Text="{Binding AddressLine2}"/>
<Label Grid.Column="2" Grid.Row="0" HorizontalOptions="EndAndExpand" VerticalOptions="EndAndExpand" Text="{Binding City}"/>
<Label Grid.Column="3" Grid.Row="0" HorizontalOptions="EndAndExpand" VerticalOptions="EndAndExpand" Text="{Binding MobileNumber}"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</StackLayout>
<!-- </Grid> -->
</pages:PopupPage>
using BottleShop.Data;
using BottleShop.Models;
using Microsoft.AppCenter.Crashes;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Xamarin.Forms.Xaml;
namespace BottleShop.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class PopupView //: ContentView
{
public ObservableCollection<OrderDetailsModel> PreviousOrderDetailsForUserLV { get; set; }
OrdersDatabaseController RecentOrdersController = new OrdersDatabaseController();
public ObservableCollection<UserModel> AllExistingUsersLV { get; set; }
UserDatabaseController UserController = new UserDatabaseController();
public bool SLOrders { get; set; }
public bool SLUsers { get; set; }
public PopupView(int OrderId, int UserId)
{
try
{
InitializeComponent();
//Show Orders PopUp
if (OrderId != -1)
{
SLOrders = true;
SLUsers = false;
List<OrderDetailsModel> RecentOrderDetailsList = RecentOrdersController.GetAllOrderDetailsByOrderId(OrderId);
PreviousOrderDetailsForUserLV = new ObservableCollection<OrderDetailsModel>(RecentOrderDetailsList as List<OrderDetailsModel>);
int startingHeightOfSL = 180;
int countOfOrderDetailRecords = PreviousOrderDetailsForUserLV.Count;
var tempHeightofStackSearchResults = countOfOrderDetailRecords * 40;
if (countOfOrderDetailRecords > 1)
{
StackSearchResultsOuter.HeightRequest = startingHeightOfSL + tempHeightofStackSearchResults;
}
else
{
StackSearchResultsOuter.HeightRequest = startingHeightOfSL;
}
UserInfoLabel.Text = "Email: " + PreviousOrderDetailsForUserLV[0].UserName + " | " + "Mobile: " + PreviousOrderDetailsForUserLV[0].UserMobileNumber;
}
else //Show Users PopUp
{
if(UserId != -1)
{
var a = 1;
SLOrders = false;
SLUsers = true;
List<UserModel> UsersList = UserController.GetUserWithId(UserId);
if (UsersList != null)
{
AllExistingUsersLV = new ObservableCollection<UserModel>(UsersList as List<UserModel>);
}
StackSearchResultsOuter.HeightRequest = 180;
}
}
BindingContext = this;
}
catch (Exception ex)
{
Crashes.TrackError(ex);
}
}
}
}
I am quite a beginner so take it easy on me. I have a collection view which is bound to an observable collection. The observable collection receives data and has the items but the Collectionview doesn't display anything at all. Could someone please help me with this. Thanks.
XAML
<CollectionView Grid.Row="1" ItemsSource="{Binding Fav}" x:Name="CVWatchItems" SelectionMode="Single" SelectionChanged="CVWatchItems_SelectionChangedAsync">
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout Padding="8, 8, 8, 0">
<Frame BorderColor="LightGray" CornerRadius="0" HasShadow="True" Padding="5">
<Grid Padding="0" ColumnSpacing="0" RowSpacing="0" Margin="2">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ffimageloading:CachedImage Source="{Binding SingleimageUrl}" Aspect="AspectFill" WidthRequest="120" HeightRequest="100" Grid.Row="0" Grid.Column="0"/>
<Grid Grid.Row="0" Grid.Column="1" Padding="5">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label Padding="0, 0, 0, 3" Text="{Binding Title}" LineBreakMode="TailTruncation" TextColor="Black" FontSize="Medium" Grid.Row="0"/>
<Label Text="{Binding Price, StringFormat='Nu.{0}'}" FontSize="Small" TextColor="Black" Grid.Row="1" HorizontalOptions="StartAndExpand" />
<Grid Grid.Row="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="7*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Label Text="{Binding location}" FontSize="Small" TextColor="Gray" Grid.Column="0" HorizontalOptions="StartAndExpand" VerticalOptions="EndAndExpand"/>
<!--Watchlist Icon-->
<Image Source="{Binding Favorite}" Grid.Column="1" Aspect="AspectFill" HeightRequest="28" Margin="2, 0" HorizontalOptions="EndAndExpand" VerticalOptions="EndAndExpand">
<Image.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped"/>
<!--Give ID to each ad and stored data is retrieved through id.-->
</Image.GestureRecognizers>
</Image>
</Grid>
</Grid>
</Grid>
</Frame>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
Code behind
public static ObservableCollection<Item> Fav { get; set; } = new ObservableCollection<Item>();
public Watchlist ()
{
InitializeComponent ();
NavigationPage.SetHasNavigationBar(this, false);
NavigationPage.SetHasBackButton(this, false);
CVWatchItems.SetBinding(CollectionView.ItemsSourceProperty, nameof(Fav));
GetFavItems();
}
private async void GetFavItems()
{
var MyFavorites = await Task.WhenAll(FirebaseDataHelper.GetFavoriteItems(allFavorites));
foreach (var favorite in MyFavorites)
{
if (favorite.Count > 0)
{
for (int i = 0; i < favorite.Count; i++)
{
favorite[i].IsFavorite = true;
if (!Fav.Any(s => s.Id == favorite[i].Id))
Fav.Add(favorite[i]);
}
}
}
}
Thanks guys.
First your observable collection is static and you never set BindingContext to your page.
public static ObservableCollection<Item> Fav { get; set; } = new ObservableCollection<Item>();
Remove static keyword from the definition of Fav, change binding in your XAML (`assign a Name to your page) like:
<ContentPage x:Name="Root" ..../>
<CollectionView Grid.Row="1" ItemsSource="{Binding Source={x:Reference Name=Root}, Path=Fav}" ..../>
Also remove binding from your code behind. Last thing, your page has to implement INotifyPropertyChanged interface because you have to tell the page that this collection changed (your collection is filled after your async task is finished) So you have to raise PropertyChanged after your collection is filled.
But maybe in your case is better and easier to set ItemsSource without binding because you are not using MVVM.
If you are in code behind of your page it is not necessary to use binding. You can set collectionview itemsource like:
private async void GetFavItems()
{
var MyFavorites = await Task.WhenAll(FirebaseDataHelper.GetFavoriteItems(allFavorites));
foreach (var favorite in MyFavorites)
{
if (favorite.Count > 0)
{
for (int i = 0; i < favorite.Count; i++)
{
favorite[i].IsFavorite = true;
if (!Fav.Any(s => s.Id == favorite[i].Id))
Fav.Add(favorite[i]);
}
}
}
CVWatchItems.ItemsSource = Fav;
}
If you will use MVVM in your application you should use bindings.
I have a usercontrol with 2 ListViews in it. One for holding a list of predefined categories and one for the list with all the categories in it.
When i place the ListViews inside a <Grid> than everything works perfect.
The working xaml code (with Grid):
<Grid Style="{StaticResource ResourceKey=ContentStyle}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<ListView x:Name="lstPredefinedCategories" Grid.Row="0" ItemsSource="{Binding PredefinedCategories}" SelectionMode="Multiple" Margin="20">
<ListView.Header>
<StackPanel>
<TextBlock Text="Voorgestelde categorieën" Style="{StaticResource TextBlockStyle}" FontWeight="SemiBold" Foreground="Black" />
<Rectangle Style="{StaticResource DividerStyle}" Fill="Black"/>
</StackPanel>
</ListView.Header>
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" Style="{StaticResource TextBlockStyle}" HorizontalAlignment="Left" TextWrapping="Wrap" Width="300" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Grid Grid.Row="1">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Margin="20,0">
<TextBlock Text="Alle categorieën" Style="{StaticResource TextBlockStyle}" FontWeight="SemiBold" Foreground="Black" />
<Rectangle Style="{StaticResource DividerStyle}" Fill="Black"/>
</StackPanel>
<TextBox x:Name="txtSearch" PlaceholderText="Zoek categorie" Grid.Row="1" Style="{StaticResource SearchboxStyle}" Margin="20,0" TextChanged="txtSearch_TextChanged" />
<Rectangle Grid.Row="2" Style="{StaticResource DividerStyle}" Margin="20, 0" />
<ListView x:Name="lstCategories" Grid.Row="3" Margin="20,10,20,0" ItemsSource="{Binding Categories}" SelectionMode="Multiple" SelectionChanged="lstCategories_SelectionChanged">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Key}" Style="{StaticResource TextBlockStyle}" HorizontalAlignment="Left" TextWrapping="Wrap" Width="300" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Rectangle Grid.Row="4" Style="{StaticResource DividerStyle}" Margin="20, 0" />
<Grid Grid.Row="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button x:Name="btnAnnuleren" Grid.Column="0" Content="Annuleren" Style="{StaticResource ButtonAnnulerenStyle}" Click="btnAnnuleren_Click"/>
<Rectangle Grid.Column="1" Fill="#A9A9A9" Width="0.5" Margin="10,0" />
<Button x:Name="btnSelecteren" Grid.Column="2" Content="Selecteren" Style="{StaticResource ButtonAnnulerenStyle}" Click="btnSelecteren_Click"/>
</Grid>
</Grid>
</Grid>
The only problem with this is that I dont get the UI behaviour that I want. If I use a grid then only the red border is scrollable (because of the ListView). But what I need is that the entire green border is scrollable.
So I want to put everything in a <ScrollViewer><StackPanel></StackPanel></ScrollViewer>.
But when I do so, I occasionally get an out-of-memory exception (sometimes the apps just freezes and close without an exception).
Here is my not working xaml with the <ScrollViewer>:
<ScrollViewer>
<StackPanel>
<ListView x:Name="lstPredefinedCategories" ItemsSource="{Binding PredefinedCategories}" SelectionMode="Multiple" Margin="20">
<ListView.Header>
<StackPanel>
<TextBlock Text="Voorgestelde categorieën" Style="{StaticResource TextBlockStyle}" FontWeight="SemiBold" Foreground="Black" />
<Rectangle Style="{StaticResource DividerStyle}" Fill="Black"/>
</StackPanel>
</ListView.Header>
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" Style="{StaticResource TextBlockStyle}" HorizontalAlignment="Left" TextWrapping="Wrap" Width="300" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Margin="20,0">
<TextBlock Text="Alle categorieën" Style="{StaticResource TextBlockStyle}" FontWeight="SemiBold" Foreground="Black" />
<Rectangle Style="{StaticResource DividerStyle}" Fill="Black"/>
</StackPanel>
<TextBox x:Name="txtSearch" PlaceholderText="Zoek categorie" Grid.Row="1" Style="{StaticResource SearchboxStyle}" Margin="20,0" TextChanged="txtSearch_TextChanged" />
<Rectangle Grid.Row="2" Style="{StaticResource DividerStyle}" Margin="20, 0" />
<ListView x:Name="lstCategories" Grid.Row="3" Margin="20,10,20,0" ItemsSource="{Binding Categories}" SelectionMode="Multiple" SelectionChanged="lstCategories_SelectionChanged">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Key}" Style="{StaticResource TextBlockStyle}" HorizontalAlignment="Left" TextWrapping="Wrap" Width="300" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Rectangle Grid.Row="4" Style="{StaticResource DividerStyle}" Margin="20, 0" />
<Grid Grid.Row="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button x:Name="btnAnnuleren" Grid.Column="0" Content="Annuleren" Style="{StaticResource ButtonAnnulerenStyle}" Click="btnAnnuleren_Click"/>
<Rectangle Grid.Column="1" Fill="#A9A9A9" Width="0.5" Margin="10,0" />
<Button x:Name="btnSelecteren" Grid.Column="2" Content="Selecteren" Style="{StaticResource ButtonAnnulerenStyle}" Click="btnSelecteren_Click"/>
</Grid>
</Grid>
</StackPanel>
</ScrollViewer>
Any thoughts on why my app is freezing or get an OOM-exception?
Update
It comes because in the 2nd ListView they are too much objects loaded. So I'm gonna try to fix it with ISupportIncrementalLoading.
Or is there an other way?
The solution was to use virtualization (ISupportIncrementalLoading) like suggested in the comments.
Here you can find my implementation class of ISupportIncrementalLoading:
public class StringKeyValueIncrementalCollection : ObservableCollection<StringKeyValue>, ISupportIncrementalLoading
{
private List<StringKeyValue> allCategories;
private int lastItem = 1;
public StringKeyValueIncrementalCollection(List<StringKeyValue> categories)
{
this.allCategories = categories;
}
public bool HasMoreItems
{
get
{
if (lastItem == allCategories.Count)
{
return false;
}
else
{
return true;
}
}
}
public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
{
CoreDispatcher coreDispatcher = Window.Current.Dispatcher;
return Task.Run<LoadMoreItemsResult>(async () =>
{
List<StringKeyValue> items = new List<StringKeyValue>();
for (int i = 0; i < count; i++)
{
items.Add(allCategories[i]);
lastItem++;
Debug.WriteLine(lastItem);
if (lastItem == allCategories.Count)
{
break;
}
}
await coreDispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
foreach (StringKeyValue item in items)
{
this.Add(item);
}
});
return new LoadMoreItemsResult() { Count = count };
}).AsAsyncOperation<LoadMoreItemsResult>();
}
}
And then my code in the ViewModel. As you can see, I use the StringKeyValueIncrementalCollection instead of a regular List<object>:
private StringKeyValueIncrementalCollection categories;
private StringKeyValueIncrementalCollection allCategories;
public StringKeyValueIncrementalCollection Categories
{
get { return categories; }
set
{
filteredCategories = value;
RaisePropertyChanged("Categories");
}
}
public async void LoadCategories()
{
List<StringKeyValue> temp = await this.openVlaanderenService.GetCategoriesData();
allCategories = new StringKeyValueIncrementalCollection(temp);
Categories = allCategories;
}
The only problem that you than have is that the ScollViewer will allow it's content to fill as much space as it wants, so the data just will keep loading. To fix that I did what was suggested in ISupportIncrementalLoading inside ScrollViewer not supported?
So I added a SizeChanged="ScrollViewer_SizeChanged" event to my ScrollViewer and in code behind set the size of the ListView based on the viewport size properties of the ScrollViewer:
private void ScrollViewer_SizeChanged(object sender, SizeChangedEventArgs e)
{
lstCategories.Height = scrollViewer.ViewportHeight;
}
As per title. The column is in a DataTemplate.
This is what I have currently:
var test = FindChildControl<ComboBox>(this, "PrintCode") as ComboBox;
test.ItemsSource = listPrintCode;
MessageBox.Show(test.Items.Count.ToString());
FindChildControl method:
private DependencyObject FindChildControl<T>(DependencyObject control, string ctrlName)
{
int childNumber = VisualTreeHelper.GetChildrenCount(control);
for (int i = 0; i < childNumber; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(control, i);
var fe = child as FrameworkElement;
// Not a framework element or is null
if (fe == null) return null;
if (child is T && fe.Name == ctrlName)
{
// Found the control so return
return child;
}
DependencyObject nextLevel = FindChildControl<T>(child, ctrlName);
if (nextLevel != null)
return nextLevel;
}
return null;
}
XAML - Template
<DataTemplate x:Key="lbCommsItemSetTemplate">
<Grid Margin="0" Width="Auto">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="Name:" />
<TextBlock Grid.Row="0" Grid.Column="0" Foreground="Blue" Margin="40,0,0,0"
Text="{Binding CommonDesc}" />
<TextBlock Grid.Row="1" Grid.Column="0" Text="Serial:" Margin="0,0,0,0"/>
<TextBlock Grid.Row="1" Grid.Column="0" Foreground="Blue" Margin="35,0,0,0"
Text="{Binding Serial}" />
</Grid>
</DataTemplate>
<DataTemplate x:Key="lbIssueTemplate">
<Grid Margin="0" Width="Auto">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition/>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="Name:" />
<TextBlock Grid.Row="0" Grid.Column="0" Foreground="Blue" Margin="50,0,0,0"
Text="{Binding CommonDesc}" />
<TextBlock Grid.Row="0" Grid.Column="1" Text="Qty:" Margin="10,0,0,0"/>
<TextBox Grid.Row="0" Grid.Column="1" Foreground="Blue" Margin="35,0,0,0"
Text="{Binding LoanQty}" PreviewTextInput="UIElement_OnPreviewTextInput" MaxLength="4"
GotKeyboardFocus="UIElement_OnGotKeyboardFocus" MaxLines="1"/>
<ComboBox x:Name="PrintCode" Grid.Row="0" Grid.Column="2" ItemsSource="{Binding}"
SelectedValuePath="PrintCode" DisplayMemberPath="PrintCode"/>
<CheckBox Grid.Row="0" Grid.Column="3" IsChecked="{Binding PrintShortSerial}"/>
</Grid>
</DataTemplate>
XAML - ListBox that implements the Template
<telerik:RadListBox Grid.Row="0" Grid.Column="2" Margin="0, 5, 5, 5"
x:Name="listBoxIssue" HorizontalAlignment="Left" VerticalAlignment="Top"
Height="690" Width="793"
ItemTemplate="{StaticResource lbIssueTemplate}" ItemsSource="{Binding}"
SelectionMode="Multiple" Drop="ListBoxIssue_OnDrop"/>
The message box is just simply to confirm that 'listPrintCode' and 'FindChildControl' is working as intended. But the ComboBox didn't display anything, even if it's just 1 ComboBox. If I apply the codes to a normal ComboBox not part of the template, it's all fine. I think there's an obvious flaw in my code, which is that there's nothing that seems to apply to all ComboBoxes in the column. So my question is, how do I bind my ItemsSource as the column of the comboboxes?
Note: The number of rows (ComboBoxes) are not fixed.