Net maui Windows platform how to change grid width according to screen width in collectionview ?

Sami 966 Reputation points
2024-02-27T08:23:48.0066667+00:00

Net maui Windows platform how to change grid width according to screen width in collectionview ? or how to set justify position of grid and width thanks..

Developer technologies | .NET | .NET MAUI
{count} votes

Accepted answer
  1. Anonymous
    2024-02-29T05:52:36.9166667+00:00

    Hello,

    I am trying to do this if it is possible to access grid name in collectionview

    I afraid you cannot get the Gird in the background code by X:Name.

    But You can try to binding a property in the ViewModel to he Gird's WidthRequest.

    <CollectionView x:Name="collectionView" HeightRequest="500" ItemsSource="{Binding Monkeys}" >
         <CollectionView.ItemTemplate>
             <DataTemplate>
                 <Grid x:Name="myGrid" WidthRequest="{Binding Source={x:Reference collectionView}, Path=BindingContext.ScreenWidth}"  Padding="10" BackgroundColor="Gray">
    

    Then please add a property in the ViewModel and implement INotifyPropertyChanged interface for property runtime change like following code.

    public class MyViewModel: INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
    
    
       public void OnPropertyChanged([CallerMemberName] string name = "") =>
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    
       public List<MyModel> Monkeys { get; set; }
    
       private double screenWidth;
    
    
       public double ScreenWidth
        {
            get { return screenWidth; }
            set { screenWidth = value;
                OnPropertyChanged();
            }
        }
    }
    

    In the End, you can set the Gird's Widthrequest in the OnAppearing method in background code.

    MyViewModel viewModel;
    public YourPage()
        {
            InitializeComponent();
         viewModel = new MyViewModel();
         BindingContext = viewModel;
    }
    
    
    protected override void OnAppearing()
    {
         base.OnAppearing();      
         // Get the screen dimensions
         var screenMetrics = DeviceDisplay.MainDisplayInfo;
         // Extract screen properties
         var screenWidth = screenMetrics.Width;
         viewModel.ScreenWidth = screenWidth; 
    }
    

    Best Regards, Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

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.