如何在数据绑定ItemsControl中访问已检查的单选按钮?

时间:2011-01-13 16:51:45

标签: silverlight data-binding windows-phone-7

我有一个绑定到字符串列表的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的完全业余爱好者。

2 个答案:

答案 0 :(得分: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 :(得分:1)

您可以通过枚举Items

来为每个RadioButton添加点击事件处理程序。
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;
}