Home > Enterprise >  Focusing on DatePicker does not work MAUI
Focusing on DatePicker does not work MAUI

Time:01-30

I found that DatePicker is missing a Placeholder. It was decided in cases where the date is not specified - to display Label instead of DatePicker. However, when clicking on Label I need to open DatePicker, but it doesn't work

.xaml:

<controls:DatePickerWithoutBottomLine
    x:Name="datePicker"
    IsVisible="{Binding DisplayWeddingDate, Mode=TwoWay}"
    Date="{Binding WeddingDate, Mode=TwoWay}" />

<Label
    IsVisible="{Binding NotDisplayWeddingDate}"
    Text="some text">

    <Label.GestureRecognizers>
        <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped" />
    </Label.GestureRecognizers>
</Label>

.xaml.cs:

private void TapGestureRecognizer_Tapped(object sender, TappedEventArgs e)
{
    var label = (Label)sender;
    var datePicker = this.FindByName<DatePicker>("datePicker");
    label.IsVisible = false;
    datePicker.IsVisible = true;
    datePicker.Focus();
}

viewmodel.cs:

public partial class HomePageViewModel : BaseViewModel
{
    [ObservableProperty]
    private DateTime? weddingDate;

    [ObservableProperty]
    private bool displayWeddingDate;

    [ObservableProperty]
    private bool notDisplayWeddingDate;

    private readonly PlanningService planningService;

    [ObservableProperty]
    private bool isRefreshing;

    public HomePageViewModel(PlanningService planningService)
    {
        this.planningService = planningService;

        InitAsync();
    }

    public override async void InitAsync()
    {
        await RefreshAsync();
    }

    [RelayCommand]
    private async Task RefreshAsync()
    {
        WeddingDate = await planningService.GetWeddingDateAsync();

        DisplayWeddingDate = WeddingDate.HasValue;
        NotDisplayWeddingDate = !DisplayWeddingDate;

        IsRefreshing = false;
    }
}

CodePudding user response:

If the datepicker has IsVisible false, it's not part of the visual tree. There is no datePicker there to focus.

datePicker.IsVisible = true;
datePicker.Focus();

Try using this.Dispatcher.Dispatch to delay focus and give it a bit of time to be rendered.

        datePicker.IsVisible = true;
        this.Dispatcher.Dispatch(() =>
        {
            datePicker.Focus();
        });

CodePudding user response:

This is an issue on Github: Fix (or don't) the behavior of calling "Focus" on Android to open the picker . From the comment , Ghostbird said the code that opens the picker has been removed from the Focus() method. So we could not use Focus() method to open the datepicker any more.

  • Related