error in grid view

Eduardo Gomez 3,651 Reputation points
2023-02-09T17:02:30.5266667+00:00

I created an avatarsHelper class, which returns me an ObservableCollection of avatars

       public static ObservableCollection<ImageSource> GetAvatars() {
            var avatars = new ObservableCollection<ImageSource>();
            for (int i = 0; i < 25; i++) {
                avatars.Add(new BitmapImage(
                    new Uri($"/Images/{i}.png", UriKind.Relative)));
            }
            return avatars;
        }

I have a profileViewodel

 public ObservableCollection<ImageSource> ImagesCollection { get; set; }

        public AsyncCommand UpdateSaveCommand { get; set; }

        public bool IsReadOnly { get; set; } = true;

        public string? BtonContent { get; set; }

        public string UserImage { get; set; }

        public string? UserId { get; set; }

        public FirebaseObject<LocalUser>? FirebaseUserObject { get; private set; }

        #region Firebase configuraion

        private readonly FirebaseServices FireService;

        private readonly string? DatabaseUrl;

        #endregion

        public ProfilePageViewModel(string userId, string databaseUrl) {

            ImagesCollection = AvatarHelper.GetAvatars();

   <ui:GridView IsEnabled="{Binding IsReadOnly}"
                         ItemsSource="{Binding ImagesCollection}">
                <Image Source="{Binding}" Stretch="UniformToFill" />
            </ui:GridView>

And I get this weird error

ItemCollection must be empty before using itemsource

the strange part is that when the app crash, it will point me here

private void PasgeSelectionItem(ModernWpf.Controls.Frame frame) {
            frame?.Navigate(SelectedItem?.NavLink);

            if (SelectedItem!.Name.Equals("CntactUS")) {
                SendEmail();
            }
            if (SelectedItem.Name.Equals("acc") && frame != null) {
                frame.LoadCompleted += (sender, eventArgs) => {
                    if (eventArgs.Content is ProfilePage page) {
                        page.DataContext = new ProfilePageViewModel(
                            UserId!, DatabaseUrl!);
                    }
                };
                frame.Navigate(SelectedItem.NavLink);

I use this code, to navigate

I can navigate fine, but when I go to the acc page, it breaks

code

https://github.com/eduardoagr/TranscribeMe

Developer technologies Windows Presentation Foundation
{count} votes

Accepted answer
  1. Peter Fleischer (former MVP) 19,341 Reputation points
    2023-02-10T07:03:19.8866667+00:00

    HI,
    you have two problems in your code:

    1. every time if you select item ("acc") you add a new handler (anonymous delegate).
    2. LoadCompleted event will be raised from outside of MainViewModel.

    Add handler to LoadCompleted only once and use parameter to transfer instance of ProfilePageViewModel:

    		private void PasgeSelectionItem(ModernWpf.Controls.Frame frame)
    		{
    			frame?.Navigate(SelectedItem?.NavLink);
    
    			if (SelectedItem!.Name.Equals("CntactUS"))
    			{
    				SendEmail();
    			}
    			if (SelectedItem.Name.Equals("acc"))
    			{
    				if (!string.IsNullOrEmpty(UserId))
    				{
    					if (frame != null)
    					{
    						SetLoadCompleted(frame);
    						frame.Navigate(SelectedItem.NavLink, new ProfilePageViewModel(UserId));
    					}
    				}
    			}
    		}
    
    #pragma warning disable CS8602
    		private bool _setLoadCompleted = false;
    		private void SetLoadCompleted(ModernWpf.Controls.Frame frame)
    		{
    			if (this._setLoadCompleted) return;
    			frame.LoadCompleted += (s, e) =>
    			{
    				if (e.Content != null && e.ExtraData != null) (e.Content as Page).DataContext = e.ExtraData;
    			};
    			_setLoadCompleted = true;
    		}
    
    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Peter Fleischer (former MVP) 19,341 Reputation points
    2023-02-11T07:13:40.5+00:00

    Hi,
    you implements invalid using of ModernWPF GridView. Try this XAML indeed:

                <!--<ui:GridView IsEnabled="{Binding IsReadOnly}"
                             ItemsSource="{Binding ImagesCollection}">
                    <Image Source="{Binding}" Stretch="UniformToFill" />
                </ui:GridView>-->
    
          <ListView ItemsSource="{Binding ImagesCollection}">
            <ListView.View>
              <GridView>
                <GridViewColumn Header="Image">
                  <GridViewColumn.CellTemplate>
                    <DataTemplate>
                      <Image Source="{Binding}" />
                    </DataTemplate>
                  </GridViewColumn.CellTemplate>
                </GridViewColumn>
              </GridView>
            </ListView.View>
          </ListView>
    

    Result:

    x

    or horizontal:

                <!--<ui:GridView IsEnabled="{Binding IsReadOnly}"
                             ItemsSource="{Binding ImagesCollection}">
                    <Image Source="{Binding}" Stretch="UniformToFill" />
                </ui:GridView>-->
    
          <ListView ItemsSource="{Binding ImagesCollection}">
            <ListView.Resources>
              <Style TargetType="GridViewColumnHeader">
                <Setter Property="Visibility" Value="Collapsed" />
              </Style>
            </ListView.Resources>
            <ListView.ItemsPanel>
              <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal" Height="150" />
              </ItemsPanelTemplate>
            </ListView.ItemsPanel>
            <ListView.View>
              <GridView>
                <GridViewColumn>
                  <GridViewColumn.CellTemplate>
                    <DataTemplate>
                      <Image Source="{Binding}" />
                    </DataTemplate>
                  </GridViewColumn.CellTemplate>
                </GridViewColumn>
              </GridView>
            </ListView.View>
          </ListView>
    

    Result:

    x

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.