ComboBox.Text显示始终为null?

时间:2017-10-24 09:23:36

标签: c# wpf combobox

我正在尝试从我的ComboBox获取文字以便切换它,但它总是会返回null。我做错了什么?

XAML:

<ComboBox Name="cbForms" SelectionChanged="cbForms_SelectionChanged" HorizontalAlignment="Left" Margin="10,289,0,0" VerticalAlignment="Top" Width="139">
    <ComboBoxItem IsSelected="True">Polygon</ComboBoxItem>
    <ComboBoxItem>Rechteck</ComboBoxItem>
    <ComboBoxItem>Dreieck</ComboBoxItem>
    <ComboBoxItem>Kreis</ComboBoxItem>
</ComboBox>

C#代码:

private void cbForms_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    string text = cbForms.Text;
    switch (text)
    {
        case "Polygon":
            {
                commandText = "SELECT f.bezeichnung, t.X, t.Y, t.id FROM figure05 f, TABLE(SDO_UTIL.GETVERTICES(f.shape)) t";
                lblAnz.Content = anzPolygon.ToString();
                break;
            }

我错过了什么吗? 感谢您提供任何帮助!

1 个答案:

答案 0 :(得分:1)

这应该有效:

private void cbForms_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (cbForms != null)
    {
        ComboBoxItem item = cbForms.SelectedItem as ComboBoxItem;
        if (item != null && item.Content != null)
        {
            string text = item.Content.ToString();
            switch (text)
            {
                case "Polygon":
                    {
                        commandText = "SELECT f.bezeichnung, t.X, t.Y, t.id FROM figure05 f, TABLE(SDO_UTIL.GETVERTICES(f.shape)) t";
                        lblAnz.Content = anzPolygon.ToString();
                        break;
                    }
            }
        }
    }
}

如果您希望在选择任何项目之前最初工作,则应设置SelectedIndex的{​​{1}}属性,而不是设置ComboBox的{​​{1}}属性}:

IsSelected