Z
Z
Zulkund2017-02-15 11:05:09
WPF
Zulkund, 2017-02-15 11:05:09

Retrieving ComboBox Item in WPF?

Good afternoon! Faced a problem with extracting the ComboBox item. The markup is like this:

<ComboBox x:Name="CB_finWell" Margin="2 0 2 0" SelectionChanged="CB_finWell_SelectionChanged" >
                        <TextBlock><Run Text="ствол"/></TextBlock>
                        <TextBlock><Run Text="значение"/></TextBlock>
                        <TextBlock><Run Text="символ"/></TextBlock>
                    </ComboBox>

In the example, it is recommended to do this:
private void CB_finWell_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox comboBox = (ComboBox)sender;
            ComboBoxItem selectedItem = (ComboBoxItem)comboBox.SelectedItem;
            MessageBox.Show(selectedItem.Content.ToString());
        }

But an exception is thrown: An unhandled exception of type 'System.InvalidCastException' occurred in DeviceConstructor.exe
I tried it in my own way, the result is 0.
TB_finWell.Text += ((TextBlock)CB_finWell.SelectedItem).Text;

Tell me, where is the error and how can I display in Showmmesage, the text of the selectedTextBlock after its selection?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Usotsky, 2017-02-15
@Zulkund

MessageBox.Show($"{((ComboBoxItem)((ComboBox)sender).SelectedItem).Content}");
For TextBlock:
MessageBox.Show($"{((TextBlock)((ComboBox)sender).SelectedItem).Text}");
Updated:
If you need to pull the Run data from the TextBlock, then use Inlines.
MessageBox.Show($"{((Run)((TextBlock)((ComboBox)sender).SelectedItem).Inlines.ElementAt(0)).Text}");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question