2011-01-13 58 views
2

我有一個ItemsControl綁定到一個字符串列表。如何訪問數據綁定ItemsControl中的選中的單選按鈕?

代碼: -

List<string> possibleAnswers; 
possibleAnswers = GetPossibleAnswers(currentQuestion); 
AnswerIC.Items.Clear(); 
AnswerIC.ItemsSource = possibleAnswers; 

的XAML: -

<ItemsControl x:Name="AnswerIC" Grid.Row="1" Margin="0,10,0,10"> 
    <ItemsControl.ItemsPanel> 
    <ItemsPanelTemplate> 
     <StackPanel x:Name="AnswerSP" Orientation="Vertical"/> 
    </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 
    <ItemsControl.ItemTemplate> 
    <DataTemplate> 
     <RadioButton GroupName="AnswerRBG" Content="{Binding}" /> 
    </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

在一個按鈕單擊事件,我試圖找到檢查單選按鈕的內容,但無法。任何人有建議嗎?我應該補充一點,我是Silverlight的一名完全業餘愛好者。

+0

請出示代碼顯示你的情況和你已經嘗試過的。 – 2011-01-13 16:59:40

+0

對不起,代碼被剝離了 – Steve 2011-01-13 17:07:56

回答

1

那麼你可以這樣做以下

1)註冊單選按鈕,單擊事件

點擊= 「RadioButton_Click」

2)不要Tag="{Binding}"

3)

private void RadioButton_Click(object sender, RoutedEventArgs e) 
{ 
    RadioButton rb = sender as RadioButton; 
    var contant= rb .tag; 
} 
1

,而不是Click事件處理程序添加到每個單選按鈕,您可以通過下面的擴展方法列舉Items

string answer = string.Empty; 

foreach (var item in AnswerIC.Items) 
{ 
    var rb = AnswerIC.ItemContainerGenerator 
        .ContainerFromItem(item).FindVisualChild<RadioButton>(); 

    if (rb.IsChecked ?? false) 
    { 
     answer = item.ToString(); 
     break; 
    } 
} 

if (string.IsNullOrEmpty(answer)) 
{ 
    MessageBox.Show("Please select an answer"); 
} 
else 
{ 
    MessageBox.Show(string.Format("You chose: {0}", answer)); 
} 

做到這一點(見http://geekswithblogs.net/codingbloke/archive/2010/12/19/visual-tree-enumeration.aspx

public static T FindVisualChild<T>(this DependencyObject instance) where T : DependencyObject 
{ 
    T control = default(T); 

    if (instance != null) 
    { 
     for (int i = 0; i < VisualTreeHelper.GetChildrenCount(instance); i++) 
     { 
      if ((control = VisualTreeHelper.GetChild(instance, i) as T) != null) 
      { 
       break; 
      } 

      control = FindVisualChild<T>(VisualTreeHelper.GetChild(instance, i)); 
     } 
    } 

    return control; 
}