I have a ItemsControl bound to a string list.
Code:-
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="Vert开发者_StackOverflow社区ical"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<RadioButton GroupName="AnswerRBG" Content="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
In a button click event, I am trying to find the content of the checked radio button and am unable to. Anyone with suggestions? And I should probably add I am a complete amateur with Silverlight.
well you can do that like following
1) Register radio button Click event
Click="RadioButton_Click"
2) Do Tag="{Binding}"
3)
private void RadioButton_Click(object sender, RoutedEventArgs e)
{
RadioButton rb = sender as RadioButton;
var contant= rb .tag;
}
Rather than add a click event handler to each RadioButton, you can do this by enumerating the 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));
}
using the following extension method (see also 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;
}
精彩评论