2017-10-24 7 views
2

ComboBoxからテキストを取得しようとしていますが、それは常にnullを返します。私は間違って何をしていますか?ComboBox.Textには常に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

これをチェックしてください:https://stackoverflow.com/questions/2961118/combobox-selectionchanged-event-has-old-value-not-new-value – praty

+3

あなたがusiでない理由はありますか?バインディング? – XAMlMAX

答えて

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; 
        } 
      } 
     } 
    } 
} 

あなたが任意の項目を選択している前に、あなたはそれが最初に仕事をしたい場合は、代わりにComboBoxItemIsSelectedプロパティを設定するのでComboBoxSelectedIndexプロパティを設定する必要があります。

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

しかし、最初の選択では機能しません( 'Polygon'項目が選択されている間は' item.Content'はnullになります)。 – Evk

+0

イベントハンドラの最初の呼び出しは、combox項目のいずれかの 'IsSelected = true'のために発生します。この呼び出しの間、 'Content'はおそらくビューの構築方法のために' null'です。これは別に処理しなければならないと思います。もう一つは 'cbForm'と' item'ヌルチェックですが、それらは必要ありません。 – Sinatr

+0

これは、SelectedIndexプロパティを設定するだけの問題です。私の編集を参照してください。 – mm8

関連する問題