2012-02-26 9 views
2

"SelectionChange"ComboBox에 대한 이벤트가 있습니다.선택한 색인의 텍스트 가져 오기 WPF ComboBox

  1. 을 나는 가능한 한 빨리
  2. 두 번째 콤보 상자는
  3. ComboBox2 반응해야 할 첫 번째 상자에서 선택한 항목에 따라 항목을 표시 두 가지 선택 상자를 가지고 : 여기

    내가 할 노력하고있어입니다 ComboBox1의 항목이 선택되었습니다.

내 문제는 SelectedIndex를 얻으려고 할 때입니다.

SelectedIndex를 확인한 후 ComboBox1.Text를 사용하면 ComboBox2가 반응하지 않도록 null이 반환됩니다.

이벤트를 강제 실행하기 위해 버튼을 배치하려고 시도했지만 제대로 작동하지 않았습니다. 포커스를 해제 할 때까지 SelectedIndex 변경되지 않는 것 같습니다. 바인딩 예전처럼

<ComboBox Height="23" HorizontalAlignment="Left" Margin="166,12,0,0" Name="cbox_year" VerticalAlignment="Top" Width="120" SelectionChanged="cbox_year_SelectionChanged"> 
     <ComboBoxItem Content="1st Year/1st Sem" /> 
     <ComboBoxItem Content="1st Year/2nd Sem" /> 
     <ComboBoxItem Content="2nd Year/1st Sem" /> 
     <ComboBoxItem Content="2nd Year/2nd Sem" /> 
     <ComboBoxItem Content="3rd Year/1st Sem" /> 
     <ComboBoxItem Content="3rd Year/2nd Sem" /> 
     <ComboBoxItem Content="4th Year/1st Sem" /> 
     <ComboBoxItem Content="4th Year/2nd Sem" /> 
    </ComboBox> 
    <ComboBox Height="23" HorizontalAlignment="Left" Margin="166,41,0,0" Name="cb_subj" VerticalAlignment="Top" Width="120" SelectionChanged="cb_subj_SelectionChanged" /> 
+0

관련 XAML을 게시 할 수 있습니까? 또한, 귀하의 코드 부분은 어떤 이벤트 처리기입니까? –

+0

상자의 SelectionChanged 이벤트의 일부입니다 – Nath

답변

3

빨리 성공하려면 ComboBox1.Text 대신 ComboBox1.SelectedValue 또는 ComboBox1.SelectedItem에 액세스 할 수 있습니다.

귀하의 주요 문제는 ComboBox1에서 선택 사항을 변경하면 ComboBox1.Text가 직접 변경되지 않으므로 텍스트 (예 : 포커스)는 텍스트가 업데이트 될 때까지 ComboBox1을 떠나야합니다. 일반적으로이 이벤트 기반 접근 방식 대신 데이터 바인딩을 사용하면 이러한 문제를 피할 수 있습니다.

+0

와우! 그것은 내 앞에 있었고 결코 그것을 사용하는 것을 생각하지 않았습니다. 고맙습니다! 거의 하루 동안 프로그래밍을 해왔고 데이터 바인딩 사용에 대한 걱정은 처음부터 다시 시작해야한다는 것이 었습니다. 고맙습니다! – Nath

1

그것은 보이지 않는다 : 여기에 두 CB의 XAML이야

if (cb_subj.SelectedIndex == ctr) 
{ 
    cb_section.Items.Clear(); 
    if (connectToDB.openConnection() == true) 
    { 
     MySqlDataAdapter comboBoxItems_seclist = new MySqlDataAdapter(); 

     MySqlCommand query = new MySqlCommand(@"SELECT section_code FROM sections 
          WHERE subject = @subj", connectToDB.connection); 
     query.Parameters.AddWithValue("@subj", cb_subj.Text); 

     comboBoxItems_seclist.SelectCommand = query; 


     System.Data.DataTable classlist = new System.Data.DataTable(); 

     comboBoxItems_seclist.Fill(classlist); 

     foreach (System.Data.DataRow row in classlist.Rows) 
     { 
      string rows = string.Format("{0}", row.ItemArray[0]); 
      cb_section.Items.Add(rows); 
     } 
     } 

     break; 
} 

:

다음은 코드의 조각인가? 바인딩을 사용하고 바인딩의 UpdateSourceTrigger 속성을 UpdateSourceTrigger.PropertyChanged로 바꿀 것을 권장합니다.

언더 레이 객체에서 u는 propertychanged 이벤트를 수신 할 수 있지만 반드시 INotifyPropertyChanged를 구현해야합니다. u는 하나의 콤보이를 위해에서 INotifyPropertyChanged

을 impliment 또한 올해 수집 을 DataContext를 설정하고 채울 수 있는지 확인

뷰에서 : 예를 들어

좀 더 구체적으로 http://www.tanguay.info/web/index.php?pg=codeExamples&id=304

보고 그리고 다른 것은 거의 같습니다. 당신이 경우 보인다

e.AddedItems[0] 

<ComboBox Name="YearCombobox" 
     ItemsSource="{Binding YearValues}" 
     SelectedValue="{Binding SelectedYear}" 
     SelectedValuePath="Key" 
     DisplayMemberPath="Value"/> 
<ComboBox Name="SubjCombobox" 
     ItemsSource="{Binding SubjValues}" 
     SelectedValue="{Binding SelectedSubj}" 
     SelectedValuePath="Key" 
     DisplayMemberPath="Value"/> 
+0

의견에 샘플 또는 스 니펫 코드를 게시 할 수 있습니까? 나는 그저 그것이 어떻게 이루어 졌는지의 패턴을 볼 필요가있다. 고마워요 – Nath

+0

오, ObservableCollection 때문에 믿을만한 UpdateSourceTrigger가 필요 없습니다. ObservableCollections 정말 강하지 만 대부분 CollectionView가 필요합니다 – rfcdejong

+0

감사합니다. – Nath

0

당신이 시도해 봤어 :

private ObservableCollection<KeyValuePair<string, string>> _yearValues = new ObservableCollection<KeyValuePair<string, string>>(); 
    public ObservableCollection<KeyValuePair<string, string>> YearValues 
    { 
     get 
     { 
      return _yearValues; 
     } 

     set 
     { 
      _yearDownValues = value; 
      OnPropertyChanged("YearValues"); 
     } 
    } 

    private string _selectedYear; 
    public string SelectedYear 
    { 
     get 
     { 
      return _selectedYear; 
     } 

     set 
     { 
      _selectedYear = value; 
      OnPropertyChanged("SelectedYear"); 
     } 
    } 

하면 OnPropertyChanged를 후크하고 XAML에서 당신의 일

public event PropertyChangedEventHandler PropertyChanged; 
    protected void OnPropertyChanged(string propertyName) 
    { 
     if (propertyName == "SelectedYear") 
     { 
      // populate subj collection which will update the combobox 
     } 
    } 

을 수행해야합니다 MVVM을 사용하지 않음 y) 때때로 SelectionChanged는 null로 반환됩니다. 다른 사람들 대신 이것을 선택하십시오.

var selectionItem = e.AddedItems[0] as ComboBoxItem; 
string text = selectionItem.Content.ToString(); 

e.RemovedItems 또한 이전에 선택한 항목을 가져올 수 있습니다보십시오.

관련 문제