如何在 C++ Winui 应用程序中将 winrt::hstring 转换为 int?

How to convert winrt::hstring to int in C++ Winui application?

我在Visual Studio中使用了名为Blank App, Package (Winui 3 in desktop)的模板。我想做一个非常简单的函数,将 2 个值加在一起。这是应用程序的样子。

这是 XAML 代码:

<StackPanel>
    <TextBox x:Name="Box1" PlaceholderText="First number"></TextBox>
    <TextBox x:Name="Box2" PlaceholderText="Second number"></TextBox>

    <Button x:Name="myButton" Click="myButton_Click">Calculate</Button>
    <TextBlock x:Name="answer"></TextBlock>
</StackPanel>

这是 C# 中的代码。

private void myButton_Click(object sender, RoutedEventArgs e)
{
    int number1 = Convert.ToInt32(Box1.Text);
    int number2 = Convert.ToInt32(Box2.Text);
    int sum = number1 + number2;
    answer.Text = sum.ToString();
}

在 C# 中一切都很好,但是当我转向 C++ 时。我遇到一些类型错误,winrt::hstring 无法转换为 int。下面是 C++ 代码

This code got problem
void MainWindow::myButton_Click(IInspectable const&, RoutedEventArgs const&)
{
    int number1 = stoi(Box1().Text());
    int number2 = stoi(Box2().Text());
    int sum = number1 + number2;
    answer().Text(L"");
}

找到方法了

std::string number_1 = winrt::to_string(Box1().Text());
std::string number_2 = winrt::to_string(Box2().Text());

int number1 = stoi(number_1);
int number2 = stoi(number_2);
int sum = number1 + number2;
winrt::hstring h_string_sum = winrt::to_hstring(sum);

answer().Text(h_string_sum);