最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - ICollectionView not Updating the UI in MAUI ContentView Page - Stack Overflow

programmeradmin1浏览0评论

I have a HomePage as ContentPage with HomePageViewModel in MAUI and it has NavigationView with NavItems, I have bind NavigationViewItem to a Relay Command in HomePageViewModel which loads a ContentView dynamically on ContentPane of NavigationView.

The ContentView page on Initializing Calls constructor and load ObservableCollection and ContentView has its own ViewModel and ItemSource as ObservableCollection for ICollectionView in XAML

Data loads perfectly fine in ObservableCollection but doesnot refresh the UI to display the values

Secondly ObservableCollection Item has Child List of Members which is nested in CollectionView unfortunately it is not also updating the UI,

Anything if I am doing wrong please help me in this , as this is the first time I am working with MAUI application

namespace KPTBMSV2.ViewModels
{
    public partial class HomePageViewModel : ObservableObject
    {
        private readonly AuthenticationService _authenticationService;
        private readonly BoardService _boardService;
        HttpClient _httpClientFactory;
        private readonly BoardsView _boardView;

        [ObservableProperty]
        private bool isAdministrator;

        [ObservableProperty]
        private string username;
        private int _editUserAccountId;

        public HomePageViewModel(AuthenticationService authenticationService, IHttpClientFactory httpClientFactory, BoardsView boardsView, BoardService service )
        {
            _authenticationService = authenticationService;
            _httpClientFactory = httpClientFactory.CreateClient("AppHttpClient");
            _boardService = service;
            _boardView = boardsView;

        }

        [RelayCommand]
        private async Task Logout()
        {
             _authenticationService.Logout();
            await Shell.Current.GoToAsync($"//{nameof(MainPage)}");
        }
        public async Task Initialize()
        {
            await CheckAuthenticationStatus();
        }
        private async Task CheckAuthenticationStatus()
        {
            await _authenticationService.FetchUserAccountSession();
            if (_authenticationService.UserAccountSession is null)
            {
                Shell.Current.GoToAsync($"//{nameof(MainPage)}");
            }else
            {
                if (_httpClientFactory.DefaultRequestHeaders.Contains("Authorization"))
                    _httpClientFactory.DefaultRequestHeaders.Remove("Authorization");

                _httpClientFactory.DefaultRequestHeaders.Add("Authorization",$"Bearer {_authenticationService.UserAccountSession.AccessToken}");
                isAdministrator = _authenticationService.IsAdmin;
                Username = _authenticationService.UserAccountSession.Username;

            }
        }

        [RelayCommand]
        private async Task OnBoardNav()
        {
            ContentPage cp = (HomePage)AppShell.Current.CurrentPage;
            RadNavigationView radNavigationView = (RadNavigationView)cp.FindByName("navigationView");
            radNavigationView.Content = _boardView;
        }

        [RelayCommand]
        private async Task BoardNavClick()
        {
            //scheldulerBoardData = await _boardService.GetScheduledBoards();
            ContentPage cp = (HomePage)AppShell.Current.CurrentPage;
            RadNavigationView radNavigationView = (RadNavigationView)cp.FindByName("navigationView");
            radNavigationView.Content = new BoardsView(_boardService);
        }
    }
}

ContentView - -- BoardView -- XAML CODE

<?xml version="1.0" encoding="utf-8" ?>
<ContentView xmlns=";
             xmlns:x=";
             x:Class="KPTBMSV2.Views.BoardsView"
             x:Name="BoardsListView"
             xmlns:viewModels ="clr-namespace:KPTBMSV2.ViewModels"
             xmlns:model ="clr-namespace:KPTBMSV2.Models"
             xmlns:viewModel="viewModels:BoardViewModel"
             xmlns:telerik=";
            >
    <VerticalStackLayout>
            <Label Text="Upcoming Events" Margin="20" FontSize="20" FontAttributes="Bold" FontFamily="MonoFurRegular"/>
        <Frame Margin="20">
            <CollectionView ItemsSource="{Binding ScheldulerBoardData}"                           
             >
                <CollectionView.ItemTemplate>
                    <DataTemplate>
                        <StackLayout Spacing="0" Orientation="Vertical">
                            <Label>
                                <Label.FormattedText>
                                    <FormattedString>
                                        <Span Text="Committee Name:" FontAttributes="Bold"/>
                                        <Span Text=" "/>
                                        <Span Text="{Binding CommitteeName}" FontAttributes="Bold" />
                                    </FormattedString>
                                </Label.FormattedText>
                            </Label>

                            <Label>
                                <Label.FormattedText>
                                    <FormattedString>
                                        <Span Text="Start Time::" FontAttributes="Bold"/>
                                        <Span Text=" "/>
                                        <Span Text="{Binding StartTime}" FontAttributes="Bold" />
                                    </FormattedString>
                                </Label.FormattedText>
                            </Label>
                            <Label>
                                <Label.FormattedText>
                                    <FormattedString>
                                        <Span Text="End Time:" FontAttributes="Bold"/>
                                        <Span Text=" "/>
                                        <Span Text="{Binding EndTime}" FontAttributes="Bold" />
                                    </FormattedString>
                                </Label.FormattedText>
                            </Label>
                           
                                                        </StackLayout>
                        
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>

        </Frame>
        <Frame Margin=" 20,0,20,0" Padding="5">
            <Label Text="ShowMembers" Margin="20,0" FontSize="20" FontAttributes="Bold" FontFamily="MonoFurRegular"/>
        </Frame>
        
               
      
      

    </VerticalStackLayout>


</ContentView>

BoardViewModel

namespace KPTBMSV2.ViewModels
{
    public partial class BoardViewModel : ObservableObject
    {
        private readonly BoardService _boardService;
        
        public BoardViewModel(BoardService boardService)
        {
            _boardService = boardService;           
            GetBoardEvents();
            //
        }

        [ObservableProperty]
        public ObservableCollection<SchedulerBoardData> scheldulerBoardData;
    
        private async Task GetBoardEvents()
        {
            ScheldulerBoardData = await _boardService.GetScheduledBoards();
            //OnPropertyChanged(nameof(ScheldulerBoardData));
        }

        [RelayCommand]
        private void EventTapped()
        {

        }
    }
}

HomePage --- XAML

<VerticalStackLayout>
     <telerik:RadNavigationView   x:Name="navigationView" AutomationId="navigationView">
         <telerik:RadNavigationView.Items>
             <telerik:NavigationViewItem ContentTemplate="{StaticResource NavigationItemStyle}" Text="Boards" x:Name="BoardViewNav" Command="{Binding BoardNavClickCommand}"/>
             <telerik:NavigationViewItem Text="Devices" x:Name="DevicesViewNav" />
             <telerik:NavigationViewItem Text="Profile" x:Name="ProfileViewNav"/>
            
         </telerik:RadNavigationView.Items>
         <telerik:RadNavigationView.Content>
            
             <Label HorizontalOptions="Center"
            VerticalOptions="Center"
            Text="{Binding SelectedItem.Text, Source={x:Reference navigationView}}" />
         </telerik:RadNavigationView.Content>
     </telerik:RadNavigationView>
 </VerticalStackLayout>

I have a HomePage as ContentPage with HomePageViewModel in MAUI and it has NavigationView with NavItems, I have bind NavigationViewItem to a Relay Command in HomePageViewModel which loads a ContentView dynamically on ContentPane of NavigationView.

The ContentView page on Initializing Calls constructor and load ObservableCollection and ContentView has its own ViewModel and ItemSource as ObservableCollection for ICollectionView in XAML

Data loads perfectly fine in ObservableCollection but doesnot refresh the UI to display the values

Secondly ObservableCollection Item has Child List of Members which is nested in CollectionView unfortunately it is not also updating the UI,

Anything if I am doing wrong please help me in this , as this is the first time I am working with MAUI application

namespace KPTBMSV2.ViewModels
{
    public partial class HomePageViewModel : ObservableObject
    {
        private readonly AuthenticationService _authenticationService;
        private readonly BoardService _boardService;
        HttpClient _httpClientFactory;
        private readonly BoardsView _boardView;

        [ObservableProperty]
        private bool isAdministrator;

        [ObservableProperty]
        private string username;
        private int _editUserAccountId;

        public HomePageViewModel(AuthenticationService authenticationService, IHttpClientFactory httpClientFactory, BoardsView boardsView, BoardService service )
        {
            _authenticationService = authenticationService;
            _httpClientFactory = httpClientFactory.CreateClient("AppHttpClient");
            _boardService = service;
            _boardView = boardsView;

        }

        [RelayCommand]
        private async Task Logout()
        {
             _authenticationService.Logout();
            await Shell.Current.GoToAsync($"//{nameof(MainPage)}");
        }
        public async Task Initialize()
        {
            await CheckAuthenticationStatus();
        }
        private async Task CheckAuthenticationStatus()
        {
            await _authenticationService.FetchUserAccountSession();
            if (_authenticationService.UserAccountSession is null)
            {
                Shell.Current.GoToAsync($"//{nameof(MainPage)}");
            }else
            {
                if (_httpClientFactory.DefaultRequestHeaders.Contains("Authorization"))
                    _httpClientFactory.DefaultRequestHeaders.Remove("Authorization");

                _httpClientFactory.DefaultRequestHeaders.Add("Authorization",$"Bearer {_authenticationService.UserAccountSession.AccessToken}");
                isAdministrator = _authenticationService.IsAdmin;
                Username = _authenticationService.UserAccountSession.Username;

            }
        }

        [RelayCommand]
        private async Task OnBoardNav()
        {
            ContentPage cp = (HomePage)AppShell.Current.CurrentPage;
            RadNavigationView radNavigationView = (RadNavigationView)cp.FindByName("navigationView");
            radNavigationView.Content = _boardView;
        }

        [RelayCommand]
        private async Task BoardNavClick()
        {
            //scheldulerBoardData = await _boardService.GetScheduledBoards();
            ContentPage cp = (HomePage)AppShell.Current.CurrentPage;
            RadNavigationView radNavigationView = (RadNavigationView)cp.FindByName("navigationView");
            radNavigationView.Content = new BoardsView(_boardService);
        }
    }
}

ContentView - -- BoardView -- XAML CODE

<?xml version="1.0" encoding="utf-8" ?>
<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="KPTBMSV2.Views.BoardsView"
             x:Name="BoardsListView"
             xmlns:viewModels ="clr-namespace:KPTBMSV2.ViewModels"
             xmlns:model ="clr-namespace:KPTBMSV2.Models"
             xmlns:viewModel="viewModels:BoardViewModel"
             xmlns:telerik="http://schemas.telerik.com/2022/xaml/maui"
            >
    <VerticalStackLayout>
            <Label Text="Upcoming Events" Margin="20" FontSize="20" FontAttributes="Bold" FontFamily="MonoFurRegular"/>
        <Frame Margin="20">
            <CollectionView ItemsSource="{Binding ScheldulerBoardData}"                           
             >
                <CollectionView.ItemTemplate>
                    <DataTemplate>
                        <StackLayout Spacing="0" Orientation="Vertical">
                            <Label>
                                <Label.FormattedText>
                                    <FormattedString>
                                        <Span Text="Committee Name:" FontAttributes="Bold"/>
                                        <Span Text=" "/>
                                        <Span Text="{Binding CommitteeName}" FontAttributes="Bold" />
                                    </FormattedString>
                                </Label.FormattedText>
                            </Label>

                            <Label>
                                <Label.FormattedText>
                                    <FormattedString>
                                        <Span Text="Start Time::" FontAttributes="Bold"/>
                                        <Span Text=" "/>
                                        <Span Text="{Binding StartTime}" FontAttributes="Bold" />
                                    </FormattedString>
                                </Label.FormattedText>
                            </Label>
                            <Label>
                                <Label.FormattedText>
                                    <FormattedString>
                                        <Span Text="End Time:" FontAttributes="Bold"/>
                                        <Span Text=" "/>
                                        <Span Text="{Binding EndTime}" FontAttributes="Bold" />
                                    </FormattedString>
                                </Label.FormattedText>
                            </Label>
                           
                                                        </StackLayout>
                        
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>

        </Frame>
        <Frame Margin=" 20,0,20,0" Padding="5">
            <Label Text="ShowMembers" Margin="20,0" FontSize="20" FontAttributes="Bold" FontFamily="MonoFurRegular"/>
        </Frame>
        
               
      
      

    </VerticalStackLayout>


</ContentView>

BoardViewModel

namespace KPTBMSV2.ViewModels
{
    public partial class BoardViewModel : ObservableObject
    {
        private readonly BoardService _boardService;
        
        public BoardViewModel(BoardService boardService)
        {
            _boardService = boardService;           
            GetBoardEvents();
            //
        }

        [ObservableProperty]
        public ObservableCollection<SchedulerBoardData> scheldulerBoardData;
    
        private async Task GetBoardEvents()
        {
            ScheldulerBoardData = await _boardService.GetScheduledBoards();
            //OnPropertyChanged(nameof(ScheldulerBoardData));
        }

        [RelayCommand]
        private void EventTapped()
        {

        }
    }
}

HomePage --- XAML

<VerticalStackLayout>
     <telerik:RadNavigationView   x:Name="navigationView" AutomationId="navigationView">
         <telerik:RadNavigationView.Items>
             <telerik:NavigationViewItem ContentTemplate="{StaticResource NavigationItemStyle}" Text="Boards" x:Name="BoardViewNav" Command="{Binding BoardNavClickCommand}"/>
             <telerik:NavigationViewItem Text="Devices" x:Name="DevicesViewNav" />
             <telerik:NavigationViewItem Text="Profile" x:Name="ProfileViewNav"/>
            
         </telerik:RadNavigationView.Items>
         <telerik:RadNavigationView.Content>
            
             <Label HorizontalOptions="Center"
            VerticalOptions="Center"
            Text="{Binding SelectedItem.Text, Source={x:Reference navigationView}}" />
         </telerik:RadNavigationView.Content>
     </telerik:RadNavigationView>
 </VerticalStackLayout>
Share Improve this question asked Feb 6 at 20:25 Shakoor AlamShakoor Alam 1871 gold badge6 silver badges21 bronze badges 3
  • are the properties of SchedulerBoardData (the class, not the property) Observable? – Jason Commented Feb 6 at 20:36
  • Inside the class of SchedulerBoardData they are not Observable as I am fetching it from a Service which consumes an API , it returns as a list and cast to ObservableCollection,then returned to the ViewModel Observable Property, its a strange behavior I am not sure it happens to anyone else , I am running the application on local device , at first it loads the Collection but the childs are not updated on the UI but during debugging if i remove the whole child ScrollView save it and paste it again it reflects on the Smartphone device ? is it normal – Shakoor Alam Commented Feb 6 at 21:28
  • don't use Frame around your collection view tryBorder – Bhavanesh N Commented Feb 7 at 2:44
Add a comment  | 

1 Answer 1

Reset to default 0

Your <DataTemplate> should specify a x:DataType if you use compiled bindings (enabled by default):

<DataTemplate x:DataType="model:SchedulerBoardData">

    <!-- content -->

</DataTemplate>

Like this or similar, depending on your namespaces.

发布评论

评论列表(0)

  1. 暂无评论