1

A sample App on .net maui with MVVM community.toolkit is running on Android simulator but not on windows machine, when i press the add button get this exception

System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'

MainViewModel.cs

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Maui.Networking;
using System.Collections.ObjectModel;

namespace ShoppingCart.ViewModel
{
    public partial class MainViewModel : ObservableObject
    {
        IConnectivity connectivity;
        public MainViewModel(IConnectivity connectivity)
        {
            items = new ObservableCollection<string>();
            this.connectivity = connectivity;
        }

        [ObservableProperty]
        ObservableCollection<string> items;

        [ObservableProperty]
        string text;

        [RelayCommand]
        async Task Add()
        {
            if (string.IsNullOrWhiteSpace(Text))
            {
                return;
            }

            if (connectivity.NetworkAccess != NetworkAccess.Internet)
            {
                await Shell.Current.DisplayAlert("Uh oh", "No Internet", "OK");
                return;
            }

            items.Add(Text);
            // add our item
            Text = string.Empty;
        }

        [RelayCommand]
        void Delete(string s)
        {
            if (items.Contains(s))
            {
                items.Remove(s);
            }
        }

        [RelayCommand]
        async Task Tap(string s)
        {
            await Shell.Current.GoToAsync($"{nameof(DetailPage)}?Text={s}");
        }

    }
}

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"
             x:Class="ShoppingCart.MainPage"
             xmlns:viewmodel="clr-namespace:ShoppingCart.ViewModel"
             x:DataType="viewmodel:MainViewModel">

    <Grid RowDefinitions="100 , Auto, *"
          ColumnDefinitions=".75* , .25*"
          Padding="10"
          RowSpacing="10"
          ColumnSpacing="10">

        <Image Grid.ColumnSpan="2" 
               Source="shopping_cart2.png" 
               BackgroundColor="Transparent"/>

        <Entry Placeholder="Enter Product"
               Text="{Binding Text}"
               Grid.Row="1" />

        <Button Text="Add" 
                Command="{Binding AddCommand}"
                Grid.Column="1"
                Grid.Row="1" />


        <CollectionView Grid.Row="2" Grid.ColumnSpan="2" 
                        ItemsSource="{Binding Items}"
                        SelectionMode="None">
            <CollectionView.ItemTemplate>
                <DataTemplate x:DataType="{x:Type x:String}">
                    <Frame x:Name="frame" CornerRadius="10" Margin="10" Padding="0" HasShadow="False"> <!--adding round corner to SwipeView-->
                        <SwipeView>
                            <SwipeView.RightItems>
                                <SwipeItems>
                                    <SwipeItem Text="Delete" 
                                           BackgroundColor="Gray" 
                                           Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodel:MainViewModel}}, Path=DeleteCommand}"
                                           CommandParameter="{Binding .}"/>
                                </SwipeItems>
                            </SwipeView.RightItems>
                            <Grid Padding="0.5">
                                <Frame>
                                    <Frame.GestureRecognizers>
                                        <TapGestureRecognizer 
                                           Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodel:MainViewModel}}, Path=TapCommand}"
                                           CommandParameter="{Binding .}"/> 
                                    </Frame.GestureRecognizers>
                                    <Label Text="{Binding .}" 
                                   FontSize="20"/>
                                </Frame>
                            </Grid>
                        </SwipeView>
                    </Frame>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>

    </Grid>   

</ContentPage>

i try cleaning up the project and rebuild but nothing

snikos
  • 29
  • 3
  • Try-catch blocks? – H.A.H. Jan 04 '23 at 10:37
  • TY for your response , i try it the same error appears . – snikos Jan 04 '23 at 10:47
  • Does this answer your question? [How to handle AccessViolationException](https://stackoverflow.com/questions/3469368/how-to-handle-accessviolationexception) – FreakyAli Jan 04 '23 at 10:56
  • I try it, no luck at all. Ty for the response ! – snikos Jan 04 '23 at 11:22
  • @snikos When you debug your exception, which row exactly throws it? – H.A.H. Jan 04 '23 at 11:50
  • @H.A.H. the line is from the auto generate code by communityToolkit.MVVM OnPropertyChanged(global::CommunityToolkit.Mvvm.ComponentModel.__Internals.__KnownINotifyPropertyChangedArgs.Text); – snikos Jan 04 '23 at 12:00
  • @snikos can you assign "" to text, just for the test? – H.A.H. Jan 04 '23 at 12:04
  • @H.A.H. same exception at this line global::Microsoft.UI.Xaml.Application.Start((p) => { var context = new global::Microsoft.UI.Dispatching.DispatcherQueueSynchronizationContext(global::Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread()); global::System.Threading.SynchronizationContext.SetSynchronizationContext(context); new App(); }); – snikos Jan 04 '23 at 12:18
  • @snikos, ok last test attempt: public ObservableCollection Items { get; } = new(); and remove the annotation above it. – H.A.H. Jan 04 '23 at 12:24
  • @H.A.H. exception in line OnPropertyChanged(global::CommunityToolkit.Mvvm.ComponentModel.__Internals.__KnownINotifyPropertyChangedArgs.Text); – snikos Jan 04 '23 at 12:39
  • 1
    @snikos the funny thing in this situation is that I know this code. Its one of the James Montemagno. More specifically, his ToolkitMessenger. And it is very hard for me to search for problems in something, that I have seen with my eyes working well. I am really sorry, that I cannot help you. – H.A.H. Jan 04 '23 at 13:21
  • 2
    @snikos found it. Its the frame around your Swipe View. Remove it, and it will work. – H.A.H. Jan 04 '23 at 14:00
  • 3
    Also, this: https://github.com/dotnet/maui/issues/6153 – H.A.H. Jan 04 '23 at 14:07
  • @H.A.H. Yes Its one of the James Montemagno samples, i put the frame to round the swipe square corners. its actually the frame cant believe it! Thanks Very Much for your help and effort ! – snikos Jan 04 '23 at 14:19
  • Congratulations! You can make the comments as a summary and post it as an answer for other people to refer to. – Guangyu Bai - MSFT Jan 05 '23 at 08:20
  • @GuangyuBai-MSFT I was thinking about it, then again, people report that this SwipeView is not working, when its the outer-most visual element in CollectionView DataTemplate. While in our findings, it was only working when it was. How can we recommend solution, that obviously causes problems on its own? We just have to hold the line, until those few thousand issues with MAUI become few hundred. That is it. – H.A.H. Jan 05 '23 at 14:06

0 Answers0