Search code examples
winui-3c++-winrt

How to get the value of a set TimePicker field programmatically


I created a WinUI 3 project. I have a timepicker field and it has the value selectedtime="11:11". I can't figure out how to get its value in code

Tried like this MainWindows.xaml

<StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
    <TimePicker x:Name="Control2" ClockIdentifier="24HourClock" Header="24 hour clock" SelectedTime="11:11" />
    <Button  x:Name="myButton" Content="Click" Click="myButton_Click"></Button>
</StackPanel>

MainWindows.xaml.cpp

void MainWindow::myButton_Click(IInspectable const&, RoutedEventArgs const&)
    {
        auto selectedTime = Control2().SelectedTime();
        auto nameTimePicker = Control2().Name(); // get property value x:Name = Control2
        myButton().Content(box_value(selectedTime));
        // This closes the program
        // selectedTime.GetString().c_str()
    }

Button text Windows.Foundation.IReference<Windows.Foundation.TimeSpan>

Can you please tell me how I can also get the text time SelectedTime = "11:11"? as I received x:Name="Control2".


Solution

  • Use std::format with std::formatter<std::chrono::duration>.

    auto selectedTime = Control2().SelectedTime().Value();
    auto nameTimePicker = Control2().Name(); // get property value x:Name = Control2
    std::string s = std::format("{:%R}", selectedTime);//"C" locale
    myButton().Content(box_value(winrt::to_hstring(s)));
    

    enter image description here

    Other information: winrt::hstring functions and operators.