Search code examples
windows-phone-8win-universal-apptimepicker

Open timePicker from textbox in uwp


I want to open a timepicker selector each time the user taps over my textbox. Is it possible? How should I do that?

I found tis post: C# WP8 Open TimePicker from code

But I cannot make it work since visual studio says that "PickerPageUri " methos is not available or not exist.


Solution

  • I want to open a timepicker selector each time the user taps over my textbox. Is it possible?

    Yes, it's possible.

    You can use the TimePickerFlyout to do this, for example:

    XAML code:

    <TextBox VerticalAlignment="Center" PointerEntered="TextboxPointEntered">
        <FlyoutBase.AttachedFlyout>
            <TimePickerFlyout />
        </FlyoutBase.AttachedFlyout>
    </TextBox>
    

    and the code behind:

    private void TextboxPointEntered(object sender, PointerRoutedEventArgs e)
    {
        FlyoutBase.ShowAttachedFlyout(sender as TextBox);
    }
    

    If you want to add FlyoutBase by code, you can do it like this:

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {          
        TextBox tbox = new TextBox();
        tbox.VerticalAlignment = VerticalAlignment.Center;
        tbox.PointerEntered += Tbox_PointerEntered;
    
        TimePickerFlyout timepickerFlyout = new TimePickerFlyout();
        FlyoutBase.SetAttachedFlyout(tbox, timepickerFlyout);
    
        rootGrid.Children.Add(tbox);
    }
    
    private void Tbox_PointerEntered(object sender, PointerRoutedEventArgs e)
    {
        FlyoutBase.ShowAttachedFlyout(sender as TextBox);
    }
    

    rootGrid in this code stands for the Grid's name of the current page.

    To show the selected time from the TimePicker in the TextBox, you can do it like this:

    private TimePickerFlyout timepickerFlyout = new TimePickerFlyout();
    private TextBox tbox = new TextBox();
    
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        tbox.VerticalAlignment = VerticalAlignment.Center;
        tbox.PointerEntered += Tbox_PointerEntered;
    
        FlyoutBase.SetAttachedFlyout(tbox, timepickerFlyout);
        timepickerFlyout.Closed += TimepickerFlyout_Closed;
    
        rootGrid.Children.Add(tbox);
    }
    
    private void Tbox_PointerEntered(object sender, PointerRoutedEventArgs e)
    {
        FlyoutBase.ShowAttachedFlyout(tbox);
    }
    
    private void TimepickerFlyout_Closed(object sender, object e)
    {
        tbox.Text = timepickerFlyout.Time.ToString();
    }