У меня большая проблема с моим приложением, оно аварийно завершает работу из-за ошибки в заголовке.
Я использую WeakMessageReferences.
Это класс, который я создал:
using CommunityToolkit.Mvvm.Messaging;
namespace NuesWarehouseMobile.Utilities
{
internal static class RefreshManager
{
public static void RequestRefresh(string viewName)
{
WeakReferenceMessenger.Default.Send(new RefreshViewMessage(viewName));
}
public static void Register(TRecipient recipient, Action action) where TRecipient : class
{
WeakReferenceMessenger.Default.Register(recipient, (r, m) => action(m));
}
public static void Unregister(TRecipient recipient) where TRecipient : class
{
WeakReferenceMessenger.Default.Unregister(recipient);
}
}
public class RefreshViewMessage
{
public string ViewName { get; }
public RefreshViewMessage(string viewName)
{
ViewName = viewName;
}
}
}
использование WeakReferences генерирует исключение.
Я пытался кэшировать представления, чтобы они не удалялись, но это не работает.
использование WeakReferences генерирует исключение.
Я пытался кэшировать представления, чтобы они не удалялись, но это не работает.
использование WeakReferences создает исключение.
Я пытался кэшировать представления, чтобы они не удалялись, но это не работает.
использование WeakReferences генерирует исключение.
Я пытался кэшировать представления, чтобы они не удалялись, но это не работает.
p>
Я пытался сделать несколько убедительных ссылок на одно и то же, но это не сработало.
Я пытался использовать разные методы для обновления своих представлений, но только сообщения работают, поэтому мне придется придерживаться этого.
Просмотр логики:
using CommunityToolkit.Mvvm.Messaging;
using NuesWarehouse.Core.Dtos;
using NuesWarehouseMobile.Core.Interfaces.Services;
using NuesWarehouseMobile.Utilities;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Windows.Input;
namespace NuesWarehouseMobile.MenuView;
public partial class DocumentiDaEvadereView : ContentView
{
private readonly IDocumentService _documentService;
private int currentPage = 1;
private int perPage = 20;
private string stato = "Aperto-Picking-Parzialmente Evaso"; //SPAZIO VUOTO
private string tipoDoc = "OrdineVendita";
private bool _isLoading;
public bool IsLoading
{
get => _isLoading;
set
{
_isLoading = value;
OnPropertyChanged(nameof(IsLoading));
}
}
public ObservableCollection Documents { get; set; }
public ICommand LoadDocumentsCommand { get; }
public ICommand NextPageCommand { get; }
public ICommand PreviousPageCommand { get; }
private int _currentPageDisplay;
public int CurrentPageDisplay
{
get => _currentPageDisplay;
set
{
_currentPageDisplay = value;
OnPropertyChanged();
}
}
public DocumentiDaEvadereView()
{
InitializeComponent();
RefreshManager.Register(this, OnRefreshViewMessageReceived);
IsLoading = true;
_documentService = Application.Current.Handler.MauiContext.Services.GetService();
Documents = new ObservableCollection();
LoadDocumentsAsync();
LoadDocumentsCommand = new Command(async () => await LoadDocumentsAsync());
NextPageCommand = new Command(async () => await LoadNextPageAsync());
PreviousPageCommand = new Command(async () => await LoadPreviousPageAsync());
//CurrentPageDisplay = currentPage;
double screenHeight = DeviceDisplay.MainDisplayInfo.Height / DeviceDisplay.MainDisplayInfo.Density;
double gridHeight = screenHeight * 0.6;
DocumentsDataGrid.HeightRequest = gridHeight;
BindingContext = this;
// Carica la prima pagina
LoadDocumentsCommand.Execute(null);
IsLoading = false;
}
private async Task LoadDocumentsAsync(int page = 1)
{
var documents = await _documentService.GetDocumentsByPage(page, perPage, tipoDoc, stato);
Documents.Clear();
foreach (var document in documents)
{
if (document.Stato == "Evaso")
{
document.StatoColor = "Green";
}
else if (document.Stato == "Parzialmente Evaso")
{
document.StatoColor = "Orange";
}
else
{
document.StatoColor = "Yellow";
}
Documents.Add(document);
}
CurrentPageDisplay = currentPage;
DocumentsDataGrid.ItemsSource = null;
DocumentsDataGrid.ItemsSource = Documents;
}
private async Task LoadNextPageAsync()
{
currentPage++;
await LoadDocumentsAsync(currentPage);
}
private async Task LoadPreviousPageAsync()
{
if (currentPage > 1)
{
currentPage--;
await LoadDocumentsAsync(currentPage);
}
}
// Metodo per aprire una nuova view
private void ApriNuovaPaginaCommand(object sender, EventArgs e)
{
IsLoading = true;
var button = sender as Button;
if (button?.CommandParameter is string documentId)
{
Debug.WriteLine(documentId);
Navigation.PushAsync(new EvasioneDocumentoPage(documentId));
}
else
{
Debug.WriteLine("====ATTENZIONE, PARAMETRO documentId NON PASSATO CORRETTAMENTE====");
}
IsLoading = false;
}
private void OnRefreshViewMessageReceived(RefreshViewMessage message)
{
if (message.ViewName == "EvasioneDocumento") // Controllo parametro
{
Debug.WriteLine("Messaggio ricevuto in DocumentsView! Aggiorno i documenti...");
_ = LoadDocumentsAsync(1); // Ricarica i documenti
}
}
~DocumentiDaEvadereView()
{
// Deregistrazione per evitare memory leaks
RefreshManager.Unregister(this);
}
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... bject-obje
.NET MAUI System.ObjectDisposeException: «Невозможно получить доступ к удаленному объекту. Имя объекта: «Microsoft.Maui. ⇐ C#
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
System.ObjectDisposeException: невозможно получить доступ к удаленному экземпляру контекста
Anonymous » » в форуме C# - 0 Ответы
- 25 Просмотры
-
Последнее сообщение Anonymous
-