public partial class MainPage : ContentPage
{
    // WORKAROUND test: on every window activation (e.g. Alt+Tab return)
    // force an ItemsSource rebind so RadDataGrid re-realizes cells and shows values
    // without needing to scroll. If true fixes the problem, this is a ready workaround.
    private const bool ApplyAltTabRefreshWorkaround = false;

    private readonly MainViewModel _viewModel = new();
    private readonly UIDataGridContext _gridContext = UIDataGridContext.Account;
    private bool _windowHooked;

    public MainPage()
    {
        InitializeComponent();
        BuildDataGrid();
    }

    protected override void OnAppearing()
    {
        base.OnAppearing();

#pragma warning disable CS0162 // Unreachable code detected (intentional: repro toggle)
        if (ApplyAltTabRefreshWorkaround && !_windowHooked && Window is not null)
        {
            Window.Activated += OnWindowActivated;
            _windowHooked = true;
        }
#pragma warning restore CS0162
    }

    private void OnWindowActivated(object? sender, EventArgs e)
    {
        Dispatcher.Dispatch(() => _viewModel.RefreshItems());
    }

    private void BuildDataGrid()
    {
        var dataGrid = new RadDataGrid
        {
            BindingContext = _viewModel,
            AutoGenerateColumns = false,
            GridLinesVisibility = GridLinesVisibility.Both,
            GridLinesThickness = 1,
            GridLinesColor = Colors.LightGray,
            UserEditMode = DataGridUserEditMode.None,
            SelectionMode = DataGridSelectionMode.Single,
            BorderThickness = 0,
            BorderBrush = Colors.Transparent,
            UserGroupMode = DataGridUserGroupMode.Disabled,
            UserFilterMode = DataGridUserFilterMode.Disabled,
            CanUserResizeColumns = true,
            EmptyContentDisplayMode = EmptyContentDisplayMode.ItemsSourceNullOrEmpty,
            EmptyContentTemplate = new DataTemplate(() => new Label
            {
                Text = "No data",
                HorizontalOptions = LayoutOptions.Center,
                VerticalOptions = LayoutOptions.Center,
                VerticalTextAlignment = TextAlignment.Center,
                HorizontalTextAlignment = TextAlignment.Center,
                TextColor = Colors.SteelBlue,
            }),
            MouseHoverStyle = new Style(typeof(DataGridMouseHoverAppearance))
            {
                Setters =
                {
                    new Setter
                    {
                        Property = DataGridBorderAppearance.BackgroundColorProperty,
                        Value = Color.FromArgb("#E6F0FA")
                    },
                }
            },
            SelectionStyle = new Style(typeof(DataGridRowBackgroundAppearance))
            {
                Setters =
                {
                    new Setter
                    {
                        Property = DataGridBorderAppearance.BackgroundColorProperty,
                        Value = Color.FromArgb("#CCE4F7")
                    }
                }
            },
        };

        dataGrid.SetBinding(RadDataGrid.ItemsSourceProperty, nameof(MainViewModel.Items));

        foreach (var config in GetColumnConfigs())
            dataGrid.Columns.Add(CreateConfiguredColumn(config));

        dataGrid.Behaviors(new EventToCommandBehavior
        {
            EventName = nameof(RadDataGrid.ColumnReordered),
            Command = _gridContext == UIDataGridContext.Account
                ? _viewModel.AccountsColumnReorderedCommand
                : _viewModel.ClientsColumnReorderedCommand,
        });

        dataGrid.Commands.Add(new AccountCellSelectedCommand(_viewModel));
        dataGrid.Commands.Add(new AccountCellDoubleTapUserCommand());
        dataGrid.Commands.Add(new AccountsLoadMoreDataCommand(_viewModel));

        RootLayout.Children.Add(dataGrid);
    }

    private static IEnumerable<DataGridColumnConfig> GetColumnConfigs()
    {
        yield return new DataGridColumnConfig { ColumnName = GridColumnNames.Name, HeaderText = "Name" };
        yield return new DataGridColumnConfig { ColumnName = GridColumnNames.Category, HeaderText = "Category" };
        yield return new DataGridColumnConfig { ColumnName = GridColumnNames.Price, HeaderText = "Price" };
        yield return new DataGridColumnConfig { ColumnName = GridColumnNames.LastSeen, HeaderText = "Last seen" };
        yield return new DataGridColumnConfig { ColumnName = GridColumnNames.InStock, HeaderText = "In stock" };
    }

    private static DataGridColumn CreateConfiguredColumn(DataGridColumnConfig config)
    {
        DataGridTextColumn column = config.ColumnName switch
        {
            GridColumnNames.Price => new DataGridNumericalColumn { CellContentFormat = "{0:N2}" },
            GridColumnNames.LastSeen => new DataGridDateColumn { CellContentFormat = "{0:dd.MM.yyyy}" },
            GridColumnNames.InStock => new DataGridBooleanColumn(),
            _ => new DataGridTextColumn(),
        };

        column.PropertyName = config.ColumnName;
        column.HeaderText = config.HeaderText;
        column.CanUserFilter = false;
        column.CanUserEdit = false;
        column.HeaderStyle = BuildHeaderStyle();

        return column;
    }

    private static Style BuildHeaderStyle()
    {
        return new Style(typeof(DataGridColumnHeaderAppearance))
        {
            Setters =
            {
                new Setter
                {
                    Property = DataGridColumnHeaderAppearance.BackgroundColorProperty,
                    Value = Color.FromArgb("#F5F5F5")
                },
                new Setter
                {
                    Property = DataGridColumnHeaderAppearance.HoverBackgroundColorProperty,
                    Value = Color.FromArgb("#F5F5F5")
                },
                new Setter
                {
                    Property = DataGridColumnHeaderAppearance.TextFontSizeProperty,
                    Value = 13.0
                },
            }
        };
    }

}