2012-11-06 83 views
0

我想在ListBox中顯示問題列表。每個ListBoxItem都包含問題和一個帶RadioButton的ListBox來顯示答案選項。第一個ListBox的ItemsSource是類Question的對象的可觀察集合。第二個ListBox的ItemsSource是QuestionClass中的list屬性:QuestionObj.Answers。 我的問題是將RadioButton屬性GroupName綁定到Question屬性QuestionObj.Index。我該如何解決這個問題?將單個屬性綁定到父項目源

這裏是類問題的代碼:

public class Question 
{ 
    private static int countQuestions; 

    private int index; 
    private string questionText; 
    private List<String> answers = new List<String>(); 

    public Question() 
    { 
     countQuestions++; 
    } 
    public Question(string type, bool isRequired, string questionText, List<String> answers = null) :this()  
    { 
     this.index = countQuestions; 
     this.questionText = questionText; 
     this.answers = answers; 
    } 

    public int Index 
    { 
     get { return index; } 
    } 
    public string QuestionText 
    { 
     get { return questionText; } 
    } 
    public List<String> Answers 
    { 
     get { return answers; } 
    } 
} 

這裏的XAML:

<ListBox x:Name="Questions" ItemsSource="{Binding QuestionList}" > 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <Grid> 
       <Grid.RowDefinitions> 
        <RowDefinition/> 
        <RowDefinition/> 
       </Grid.RowDefinitions> 
       <Label Grid.Row="0" Content="{Binding QuestionText}"/> 
       <ListBox x:Name="AnswerOptions" Grid.Row="1" ItemsSource="{Binding Answers}"> 
        <ListBox.ItemTemplate> 
         <DataTemplate> 
          <RadioButton Content="{Binding}" GroupName={Binding ??????}/> 
         </DataTemplate> 
        </ListBox.ItemTemplate> 
       </ListBox> 
      </Grid> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

回答

0

編輯: 更改selectedIndex設置爲SelectedItem.Index

<RadioButton Content="{Binding}" 
      GroupName={Binding ElementName=Questions, Path=SelectedItem.Index}/> 

看一看這裏。 www.nbdtech.com/Free/WpfBinding.pdf

+0

感謝您的鏈接。這是一個很好的展望。 –

+0

您的解決方案在此處不起作用,因爲所有單選按鈕都會獲得SelectedIndex的值。我需要每個問題的唯一索引。 –

+0

我編輯了我的答案。 – menty

相關問題