Mahapps : ScrollViewer update list on event KeyDown in WPF ( C # ) - c#

I have a problem I can not solve.
As you can see in the picture , there is a label , a textobx and a ScrollViewer .
Now , I have to update the ScrollViewer when the user searches through the textbox .
Part of an event every time you make a keydown .
So if I write Statut ... should put first in the file list with the names "statuto rai"
the list can have N elements
Image list:
Xaml code:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="25"></RowDefinition>
<RowDefinition Height="25"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Background="GhostWhite"/>
<Grid Grid.Row="1" Background="Gray"/>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center">Documenti allegati</TextBlock>
<Border Grid.Row="1" Margin="3" BorderBrush="White" Height="22" Background="#fff">
<TextBox BorderBrush="#465E76" KeyDown="TextBox_KeyDown" BorderThickness="0" FontSize="10" Background="#fff" Foreground="#565656" controls:TextBoxHelper.Watermark="Ricerca Locale" FontFamily="{StaticResource Lato Thin}" HorizontalContentAlignment="Center" ></TextBox>
</Border>
<ScrollViewer Grid.Row="2" VerticalScrollBarVisibility="Hidden" PanningMode="Both" Name="scrollDocuments">
<ItemsControl ItemsSource="{Binding Path=attachmentsList}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Grid.Column="0" Grid.Row="0">
<Button Grid.ColumnSpan="2">
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="450"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="60"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Background="#fff"></Grid>
<TextBlock Foreground="#565656" FontFamily="{StaticResource Lato Semibold}" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="10" Margin="10,3,0,0" Style="{DynamicResource Lato-Semibold}" Text="{Binding contList}"/>
<Image Source="/Resources/Images/icon-document-browser.png" HorizontalAlignment="Left" Margin="22,-12,0,0" Width="22"/>
<TextBlock Foreground="#565656" FontFamily="{StaticResource Lato Semibold}" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="10" Margin="21,32,0,0" Style="{DynamicResource Lato-Semibold}" Text="{Binding FileSizeConverted}"/>
<TextBlock Foreground="#565656" FontFamily="{StaticResource Lato Semibold}" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="12" Margin="55,-10,0,0" Style="{DynamicResource Lato-Semibold}" Text="{Binding Name}"/>
<TextBlock Foreground="#565656" FontFamily="{StaticResource Lato Semibold}" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" FontSize="12" Margin="55,-10,10,0" Style="{DynamicResource Lato-Semibold}" Text="{Binding ModifiedDate}"/>
<TextBlock Foreground="#565656" FontFamily="{StaticResource Lato Semibold}" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" FontSize="10" Margin="55,25,10,0" FontWeight="Bold" Style="{DynamicResource Lato-Semibold}" Text="Nessuna copia locale"/>
<Border Grid.Row="0" Grid.ColumnSpan="2" BorderBrush="#DDD" BorderThickness="0,0,0,1"></Border>
</Grid>
</ControlTemplate>
</Button.Template>
</Button>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
<Viewbox Grid.Row="2" Name="testoNessunAllegato" Visibility="Collapsed" Margin="20">
<TextBlock Text="Nessun allegato disponibile."></TextBlock>
</Viewbox>
</Grid>
CodeBehind event code:
private void TextBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
string find = ((TextBox)sender).Text;
attachmentsList = attachmentsList.Where(x => x.Name == find).ToList();
InitializeComponent();
}
in practice I do the intelligiente research, so every time I insert a letter filtrale list , and print it again , of course real time .
I hope I explained myself .
Thank you

I see you use bindings, in this case there is a much better stuff to reach your goal. It's CollectionView.
Here is a simple app for you which more or less fullfill your requirements:
View
<StackPanel Orientation="Horizontal">
<Label Content="Search" />
<TextBox MinWidth="30" Text="{Binding FilterText, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
<ListBox ItemsSource="{Binding Data}" />
UpdateSorceTrigger=PropertyChanges updates FilterText in ViewModel every time when you press any key.
Data is a ICollectionView
ViewModel
public ICollectionView Data { get; private set; }
...
// Create default view for the list
Data = CollectionViewSource.GetDefaultView(list);
// Set filter delegate for CollectionView
Data.Filter = FilterData;
....
private bool FilterData(object obj)
{
DataContainer cont = (DataContainer)obj;
return string.IsNullOrEmpty(FilterText) || cont.Name.StartsWith(FilterText, StringComparison.OrdinalIgnoreCase);
}
private string myfiltertext;
public string FilterText
{
get { return myfiltertext; }
set
{
myfiltertext = value;
// Refresh collection view after Filter text modification
Data.Refresh();
}
}

Related

How can I navigate in WPF MVVM page

I have viewlist in which contain elements. When I click on them, my ItemViewModel handler clicks. Then I can select information about that element. Afthe I must to open new page in which will be all information about it. For example like hypertext in browser.
<Border MaxHeight="300" MaxWidth="1140" CornerRadius="25" Margin="73,269,65,182">
<Grid x:Name="MainGrid" RenderTransformOrigin="0.5,0.5" Margin="0,0,10,-3">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ListView Width="1031" ItemsSource="{Binding GetTopItem}"
ScrollViewer.VerticalScrollBarVisibility="Disabled" HorizontalAlignment="Left" ScrollViewer.HorizontalScrollBarVisibility="Hidden"
Background="{x:Null}" BorderBrush="{x:Null}" Foreground="#DD000000"
x:Name="ListBook">
<ListView.DataContext>
<vm:BookMainVM/>
</ListView.DataContext>
<ListView.ItemTemplate>
<DataTemplate>
<Border HorizontalAlignment="Left" CornerRadius="25,25,25,25" BorderThickness="1" BorderBrush="#FF474747" Height="288" Margin="0,0,0,0" MouseDown="Border_MouseDown" >
<Grid Grid.Column="0" Height="Auto" Width="216" Margin="-1" IsEnabled="False">
<Grid.InputBindings>
<MouseBinding Gesture="LeftClick"
Command="{Binding DataContext.DelegateCommands,
RelativeSource={RelativeSource AncestorType=ListView}}"
CommandParameter="{Binding}">
</MouseBinding>
</Grid.InputBindings>
<Grid.RowDefinitions>
<RowDefinition Height="49*"/>
<RowDefinition Height="5*"/>
<RowDefinition Height="18*"/>
</Grid.RowDefinitions>
<Border CornerRadius="25,25,0,0" RenderTransformOrigin="0.5,0.5">
<Border.Background>
<ImageBrush ImageSource="{Binding Img_src}" Stretch="Fill" />
</Border.Background>
</Border>
<Label Content="{Binding Rate}" Background="#FFBFBFBF" RenderTransformOrigin="0.5,0.5" Grid.Row="1" FontSize="11" FontFamily="Meiryo UI" HorizontalContentAlignment="Center"/>
<Border CornerRadius="0,0,25,25" Grid.Row="2" Background="#FF8F8F8F">
<TextBlock Margin="6,0,0,0" Text="{Binding Name}" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Grid.Row="2" Height="61" Width="190"/>
</Border>
</Grid>
</Border>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Border>
class ItemMainVM:ViewModel
{
private LibraryModel libraryModel;
private ItemDb itemsDb;
private const string Dir = "D:\\repos\\Frame\\Frame\\src";
public ItemMainVM()
{
libraryModel = new LibraryModel();
itemsDb = new BooksDb();
DelegateCommands = new DelegateCommand(o => EventHandler(o));
}
public ObservableCollection<BookPreviewInfo> GetTopItem
{
get
{
return libraryModel.GetTopItems();
}
}
public ICommand DelegateCommands { get; }
public void EventHandler(dynamic item)
{
itemDb.SelectItemId(item.Id);
}
}
Code Behind is empty.
When I click an element and executing EventHandler in ItemMainVM. And next must be create new page with new ElementViewModel.
ElementViewModel should to get information about element in ItemMainVM.

How to set Textbox value on click command

On my Resources.xaml(Resource Dictionary) I have a DataTemplate :
<DataTemplate x:Key="ProductDetailsContentTemplate">
<StackPanel Orientation="Vertical" >
<Viewbox Margin="27,0,28,0" Height="200" >
<Image UWPUtil:ImageExtensions.CachedUriSource="{Binding ImageUri}" />
</Viewbox>
<TextBlock Text="Description" Style="{StaticResource CaptionTextBlockStyle}" FontWeight="Bold" FontSize="24"/>
<TextBlock Text="{Binding ProductDescription}" Style="{StaticResource SubtitleTextBlockStyle}" FontSize="30"/>
<TextBlock Text="Barcode" Style="{StaticResource CaptionTextBlockStyle}" FontWeight="Bold" FontSize="24"/>
<TextBlock Text="{Binding Barcode}" Style="{StaticResource SubtitleTextBlockStyle}" FontSize="30"/>
<TextBlock Text="Weight" Style="{StaticResource CaptionTextBlockStyle}" FontWeight="Bold" FontSize="24"/>
<TextBlock Text="{Binding Weight}" Style="{StaticResource SubtitleTextBlockStyle}" FontSize="30"/>
<TextBlock Text="Quantity" Style="{StaticResource CaptionTextBlockStyle}" FontWeight="Bold" FontSize="24"/>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="25*"/>
<ColumnDefinition Width="50*"/>
<ColumnDefinition Width="25*"/>
</Grid.ColumnDefinitions>
<Button x:Name="SubtractQytyButton" Grid.Column="0" Content="-" FontSize="24" HorizontalAlignment="Stretch"
Margin="5,0" Style="{StaticResource TestButtonStyle}" FontWeight="ExtraBold"
Click="SubQytyButton_Click"/>
<TextBox x:Name="QuantityTextBox" Grid.Column="1" HorizontalAlignment="Stretch" FontSize="24" Margin="5,0"
KeyDown="Quantity_Keydown" TextChanging="Quantity_TextChanging"
Text="{Binding Quantity, Mode=TwoWay, Converter={StaticResource DecmialConverter}}" MaxLength="5" TextAlignment="Center"/>
<Button x:Name="AddQytyButton" Grid.Column="2" Content="+" FontSize="24" HorizontalAlignment="Stretch"
Margin="5,0" Style="{StaticResource TestButtonStyle}" FontWeight="ExtraBold"
Click="AddQytyButton_Click"/>
</Grid>
</StackPanel>
</DataTemplate><br>
I file nested it using the File Nesting from Mads Kristensen , here is the thread: https://marketplace.visualstudio.com/items?itemName=MadsKristensen.FileNesting
so I have a Resources.xaml.cs on my ResourceDictionary
my problem is I want to set my QuantityTextBox Value on AddQytyButton and SubQytyButton click command, here is my click command event:
private void AddQytyButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
//does not exist in the current context
QuantityTextBox.Text = "test";
}
OR
private void AddQytyButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
Button btn = sender as Button;
// this is not working as null reference
var textbox = (btn.Parent as StackPanel).Children[1] as TextBox;
}
Thanks,
NicoTing
You should cast btn.Parent to a Grid instead of a StackPanel since you are using the former in your XAML.
var textbox = (btn.Parent as Grid).Children[1] as TextBox;

Click event on an item template

I have this wpf code for my listbox item:
<ListBox x:Name="icTodoList" ItemsSource="{Binding ListControleMachine}" Grid.Column="3">
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="{Binding borderColor}" BorderThickness="2" Margin="0,0,0,1">
<Grid Margin="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="30"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="130"/>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="120"/>
</Grid.ColumnDefinitions>
<CheckBox x:Name="check_action" Content="" HorizontalAlignment="Left" VerticalAlignment="Top" IsChecked="{Binding ActionCheked,Mode=TwoWay}"/>
<Ellipse x:Name="E_Ping" HorizontalAlignment="Left" Fill="{Binding PingDotColor}" Height="10" Width="10" Margin="2,4,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.2,-1.182" Grid.Column="1"/>
<TextBlock Text="{Binding titlePing}" Grid.Column="2" MouseDown="TextBlock_MouseDown" Tag="{Binding ComputerName}"/>
<TextBlock Text="{Binding titlePing}" Grid.Column="2" MouseDown="TextBlock_MouseDown" Tag="{Binding ComputerName}"/>
<TextBlock Text="{Binding titleDcai}" Grid.Column="3" MouseDown="TextBlock_MouseDown" Tag="{Binding ComputerName}"/>
<TextBlock Text="{Binding titleAd}" Grid.Column="4" MouseDown="TextBlock_MouseDown" Tag="{Binding ComputerName}"/>
<TextBlock Text="{Binding FPACtitle}" Grid.Column="5" MouseDown="TextBlock_MouseDown" Tag="{Binding ComputerName}"/>
<TextBlock Text="{Binding titleMcAfee}" Grid.Column="6" MouseDown="TextBlock_MouseDown" Tag="{Binding ComputerName}"/>
<TextBlock Text="{Binding gkUser}" Grid.Column="7" MouseDown="TextBlock_MouseDown" Tag="{Binding ComputerName}"/>
<TextBlock Text="{Binding titleservicestat}" Grid.Column="8" MouseDown="TextBlock_MouseDown" Tag="{Binding ComputerName}"/>
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
As you can see I have a "TextBlock_MouseDown" on each textbox
Then the c# code.
private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
{
TextBlock t = sender as TextBlock;
DetailedView.DataContext = ListControleMachine.Where(x => x.ComputerName == t.Tag.ToString());
DetailedView.Visibility = System.Windows.Visibility.Visible;
}
Ok, so it does what I need basically it pop a view with data rebinded to it.
but I'm pretty sure its not a clean way to do it.
first I don't wont event on each textblock but on the listboxitem it self (but I don't know how to pass computername argument this way).
second and may bee my only problem I think I don't have to search my collection and rebind my new view with this:
DetailedView.DataContext = ListControleMachine.Where(x => x.ComputerName == t.Tag.ToString());
for be clear how to click an item template and pop a view that will contain actual listbox item binded data?
try set DataContext via binding to SelectedItem of ListBox
<DetailedView DataContext="{Binding Path=SelectedItem, ElementName=icTodoList, Mode=OneWay}"/>
or equivalent code
var binding = new Binding
{
Path = new PropertyPath("SelectedItem"),
ElementName = "icTodoList",
Mode = BindingMode.OneWay
};
BindingOperations.SetBinding(DetailedView, Control.DataContextProperty, binding);
another approach
ListBox has SelectionChanged event
<ListBox Name="icTodoList"
SelectionChanged="IcTodoList_OnSelectionChanged">
</ListBox>
event handler
private void IcTodoList_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
DetailedView.DataContext = icTodoList.SelectedItem;
DetailedView.Visibility = System.Windows.Visibility.Visible;
}
Tag values and TextBlock_MouseDown handler will be not necessary

Grouped Listview windows-phone

I'm trying to to show a grouped Listview based on this class
private class EInfo
{
public double JD { get; set; }
public string Date { get; set; }
public string Time { get; set; }
public string Details { get; set; }
public string MoreDetails { get; set; }
public string Icon { get; set; }
}
private List<EInfo> MEphemeries = new List<EInfo>();
This is how I grouped and ordered all the elements in every group:
IEnumerable<IGrouping<string, EInfo>> query = MEphemeries.GroupBy(pet => pet.Details);
foreach (var group in query)
{
Debug.WriteLine("Group {0}", group.Key);
group.OrderBy(a => a.JD);
foreach (var user in group)
{
Debug.WriteLine(" {0}", user.Date);
}
}
listviewME.ItemsSource = query;
And here goes the XAML:
<SemanticZoom Grid.Row="1" Background="Black" x:Name="semanticZoom" >
<SemanticZoom.ZoomedInView>
<ListView x:Name="listviewME" IncrementalLoadingThreshold="15">
<!--<ListView.SemanticZoomOwner>
<SemanticZoom/>
</ListView.SemanticZoomOwner>-->
<ListView.Header>
<!-- table header-->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition x:Name="listviewMEHeader0" Width="140"/>
<ColumnDefinition x:Name="listviewMEHeader1" Width="60"/>
<ColumnDefinition x:Name="listviewMEHeader2" Width="*"/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="0" Background="{StaticResource MediumGreyThemeColor}" Margin="0, 0.5, 0, 0.5">
</Grid>
<Grid Grid.Column="1" Background="{StaticResource MediumGreyThemeColor}" Margin="0, 0.5, 0, 0.5">
</Grid>
<Grid Grid.Column="2" Background="{StaticResource MediumGreyThemeColor}" Margin="0, 0.5, 0, 0.5">
</Grid>
</Grid>
</ListView.Header>
<ListView.ItemTemplate>
<DataTemplate>
<Grid Background="Black" Margin="0,0,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="140"/>
<ColumnDefinition Width="60"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="0" Background="{StaticResource DarkGreyThemeColor}" Margin="0, 0, 0, 0.5">
<StackPanel>
<TextBlock Text="{Binding Date}" Margin="5" HorizontalAlignment="Center" VerticalAlignment="Center" Style="{StaticResource FlyoutPickerTitleTextBlockStyle}"/>
<TextBlock Text="{Binding Time}" Margin="5,0,5,5" HorizontalAlignment="Center" VerticalAlignment="Center" Style="{StaticResource BaseTextBlockStyle}" FontSize="14" Foreground="{StaticResource LightGreyThemeColor}"/>
</StackPanel>
</Grid>
<Grid Grid.Column="1" Background="{StaticResource DarkGreyThemeColor}" Margin="0, 0, 0, 0.5">
<!--<Rectangle Height="25" Width="25" Margin="0" Fill="{StaticResource MoonThemeColor}" RadiusX="12.5" RadiusY="12.5" />
<Rectangle Height="35" Width="35" Margin="0" Stroke="{Binding Color}" StrokeThickness="2" RadiusX="17.5" RadiusY="17.75" />-->
<Image Height="30" Width="30" Margin="0" Source="{Binding Icon}" Stretch="Uniform" />
</Grid>
<Grid Grid.Column="2" Background="{StaticResource DarkGreyThemeColor}" Margin="0, 0, 0, 0.5" Width="{Binding ActualWidth, ElementName=listviewMEHeader2}">
<StackPanel>
<TextBlock Text="{Binding Details}" Margin="5" HorizontalAlignment="Center" VerticalAlignment="Center" Style="{StaticResource FlyoutPickerTitleTextBlockStyle}" Foreground="{StaticResource VeryLightGreyThemeColor}"/>
<TextBlock Text="{Binding MoreDetails}" Margin="5,0,5,5" HorizontalAlignment="Center" VerticalAlignment="Center" Style="{StaticResource BaseTextBlockStyle}" FontSize="14" Foreground="{StaticResource LightGreyThemeColor}"/>
</StackPanel>
</Grid>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.GroupStyle>
<GroupStyle HidesIfEmpty="True">
<GroupStyle.HeaderTemplate>
<DataTemplate>
<Border Grid.Column="0" Grid.ColumnSpan="3" MinWidth="400" BorderThickness="2" BorderBrush="Blue" Background="AliceBlue" Margin="0,10,5,0" CornerRadius="1">
<TextBlock Foreground="White" Text="{Binding Key}"
Margin="10,2,2,5" TextTrimming="WordEllipsis" TextWrapping="NoWrap"
FontWeight="SemiBold" FontSize="10" />
</Border>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListView.GroupStyle>
</ListView>
</SemanticZoom.ZoomedInView>
<SemanticZoom.ZoomedOutView>
<ListView Margin="5" ItemsSource="{Binding query}" Background="White">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Height="99" Margin="16">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Border Background="{StaticResource MediumDarkGreyThemeColor}" Width="200" Height="111">
<Grid>
<TextBlock Text="{Binding Group.Key}" Style="{ThemeResource SubheaderTextBlockStyle}" />
</Grid>
</Border>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</SemanticZoom.ZoomedOutView>
</SemanticZoom>
The question is that all the info is grouped Ok, every group with its key, its list of elements correctly ordered by date, but the listview doesn't shows any info. It only some empty blocks (the number of block is the same to the number of groups).
What is the problem? How I can fix this?
This is what I get:
This is what I want to achieve:
Thank you in advance!
Some stuff I see that might fix your problems:
1) Change your private class EInfo to public
2) Your first ListView does not have ItemsSource set while your second LiewView has it set to ItemsSource="{Binding query}"
3) You can group your ListView and GridView nicely by using a CollectionViewSource see here : CollectionViewSource example
4) Or you can do it manually by Grouping it into an AlphaKeyGroup, I have a working example here : AlphaKeyGroup
Last idea, is to check the output of your GroupBy code vs the CollectionViewSource and AlphaKeyGroup in the debugger to see if they match up.

Out of memory exception while using <ScrollViewer> with multiple ListViews in it

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

Categories

Resources