I am new to .NET Maui and I am creating my first application that first checks the dll file for interface implementation, then the user enters a number and the program should output all prime numbers up to it. The problem came up in the visualization, I have the application itself hangs when a large number is processed, so I decided to make it asynchronous. This didn’t help, because the visualization itself hangs when it tries to list these numbers. Then I decided to add gradual scrolling, but it doesn’t work. In the debug this event just doesn’t work.
This is MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:PrimeNumApp"
x:Class="PrimeNumApp.MainPage">
<VerticalStackLayout
Padding="30,0"
Spacing="25">
<Label
Text="Cписок простых чисел"
Style="{StaticResource Headline}"
SemanticProperties.HeadingLevel="Level1" />
<Image
Source="kitten.gif"
HeightRequest="200"
HorizontalOptions="Center"
IsAnimationPlaying="True" />
<Entry
x:Name="NumberEntry"
Placeholder="Введите число" />
<StackLayout
Orientation="Horizontal"
Spacing="5"
>
<Button
x:Name="LoadBtn"
Text="Загрузить сборку"
Clicked="OnLoadClicked"
HorizontalOptions="FillAndExpand"
BackgroundColor="Gray" />
<Button
x:Name="StartBtn"
Text="Посчитать"
Clicked="OnStartClicked"
IsEnabled="False"
HorizontalOptions="FillAndExpand"
BackgroundColor="DarkRed" />
</StackLayout>
<CollectionView x:Name="PrimeNumCollection"
RemainingItemsThreshold="5"
RemainingItemsThresholdReached="OnCollectionViewRemainingItemsThresholdReached">
<CollectionView.ItemsLayout>
<LinearItemsLayout Orientation="Vertical" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding}"
TextColor="White"/>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</VerticalStackLayout>
</ContentPage>
This is MainPage.xaml.cs
using Contract;
using Microsoft.Maui.Controls;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Reflection;
using System.Text;
namespace PrimeNumApp
{
public partial class MainPage : ContentPage, INotifyPropertyChanged
{
private bool _isImplemented;
private Assembly _assembly;
private string _realizationPath;
private IPrimeGenerator _primeNumberGenerator;
private const int PageSize = 5;
private int _currentPage = 0;
public ObservableCollection<int> DisplayablePrimeNums { get; set; }
private List<int> _allPrimeNumbers = new List<int>();
public MainPage()
{
InitializeComponent();
DisplayablePrimeNums = new ObservableCollection<int>();
PrimeNumCollection.ItemsSource = DisplayablePrimeNums;
PrimeNumCollection.RemainingItemsThresholdReached += OnCollectionViewRemainingItemsThresholdReached;
}
public async void OnStartClicked(object sender, EventArgs e)
{
if (int.TryParse(NumberEntry.Text, out int number))
{
try
{
_allPrimeNumbers = await Task.Run(() => _primeNumberGenerator!.GetPrimeNumbers(number));
DisplayablePrimeNums.Clear();
LoadNextPage();
}
catch (Exception ex)
{
await DisplayAlert("Ошибка", ex.Message, "OK");
}
}
else
{
await DisplayAlert("Ошибка", "Вы ввели не натуральное число", "OK");
}
}
private void LoadNextPage()
{
foreach (int number in _allPrimeNumbers.GetRange(_currentPage, PageSize))
{
DisplayablePrimeNums.Add(number);
}
_currentPage += PageSize;
}
public void OnCollectionViewRemainingItemsThresholdReached(object sender, EventArgs e)
{
LoadNextPage();
}
public async void OnLoadClicked(object sender, EventArgs e)
{
await PickDll();
}
private async Task PickDll()
{
var customFileType = new FilePickerFileType(
new Dictionary<DevicePlatform, IEnumerable<string>>
{
{ DevicePlatform.WinUI, new[] { ".dll" } },
});
try
{
var result = await FilePicker.PickAsync(new PickOptions()
{
FileTypes = customFileType,
PickerTitle = "Выберите файл формата .dll"
});
if (result != null)
{
_realizationPath = result.FullPath;
await LoadDll();
}
}
catch (Exception ex)
{
await DisplayAlert("Ошибка", "Ошибка при загрузке сборки: " + ex.Message, "OK");
}
}
private async Task LoadDll()
{
_assembly = Assembly.LoadFrom(_realizationPath);
await CheckContractRealization();
}
private async Task CheckContractRealization()
{
_isImplemented = _assembly.GetTypes().Any(type => type.GetInterfaces().Contains(typeof(IPrimeGenerator)));
if (_isImplemented)
{
LoadBtn.BackgroundColor = Colors.Green;
StartBtn.IsEnabled = true;
StartBtn.BackgroundColor = Colors.Gray;
var primeGeneratorType = _assembly.GetTypes()
.Where(type => typeof(IPrimeGenerator).IsAssignableFrom(type) && type.IsClass)
.Select(type => type)
.First();
_primeNumberGenerator = (IPrimeGenerator)Activator.CreateInstance(primeGeneratorType)!;
}
else
{
await DisplayAlert("Ошибка", "Реализация не соответсвует контракту", "OK");
}
}
}
}
I tried changing and removing the scroller itself, displaying DataTemplate inside CollectionView, it didn’t work
Марат is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.