简体   繁体   中英

How do I get the user selection item from a ComboBox in WinUI3 C++/WinRT?

I would like to get the selected user item from a ComboBox in WinUI3 C++/WinRT. There is this code in XAML:

<ComboBox x:Name="ComboTranslate" HorizontalAlignment="Center" Header="Translate to" SelectionChanged="ComboBox_SelectionChanged" SelectedIndex="0" Width="200" Margin="0,15,0,0">
        <x:String>2</x:String>
        <x:String>8</x:String>
        <x:String>10</x:String>
        <x:String>16</x:String>
</ComboBox>

In C# in WinUI3 it is implemented as follows:

private void ColorComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    // Add "using Windows.UI;" for Color and Colors.
    string colorName = e.AddedItems[0].ToString();
    Color color;
    switch (colorName)
    {
        case "Yellow":
            color = Colors.Yellow;
            break;
        case "Green":
            color = Colors.Green;
            break;
        case "Blue":
            color = Colors.Blue;
            break;
        case "Red":
            color = Colors.Red;
            break;
    }
    colorRectangle.Fill = new SolidColorBrush(color);
}

How can you do this on C++/WinRT?

Here's how I'm doing it on my pet project's PopUpButton class, using the SelectedIndex() method:

void
CAUIPopUpButton::HandleHostSelectionChangedEvent(
    Windows::Foundation::IInspectable const & /* sender */,
    Windows::UI::Xaml::Controls::SelectionChangedEventArgs const & /* event */ )
{
    M_LOG_METHOD( HandleHostSelectionChangedEvent )

    TIndex newSelectedItem;

    newSelectedItem = _hUIElement.as< Windows::UI::Xaml::Controls::ComboBox >().SelectedIndex();

    ValueChanged( newSelectedItem );
}

Basically, I'm not using the information of the sender and event as I manually connect the event handler to the ComboBox, the _hUIElement in the code above.

_hUIElement = Windows::UI::Xaml::Controls::ComboBox();
_hUIElement.as< Windows::UI::Xaml::Controls::ComboBox >().SelectionChanged( { this, & CAUIPopUpButton::HandleHostSelectionChangedEvent } );

Please don't judge my C++ style: I'm a bit old school and not a big fan of XAML !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM