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.