Professional Documents
Culture Documents
Radio Button Silver Light
Radio Button Silver Light
In this article we are going to learn how we can create radio buttons at runtime and also we learn how to set event at runtime. When it can be used: 1. When you want to make choice we can go for Radio Button. 2. Group by Group selection is possible.
Step 1:
Step 2:
Step 3:
Used Namespaces:
Step 4:
List<CompanyProduct> companyProducts = new List<CompanyProduct>(); companyProducts.Add(new CompanyProduct("Visual Studio", "MS", "MS", "MSVS")); companyProducts.Add(new CompanyProduct("SQl Server", "MS", "MS", "MSS")); companyProducts.Add(new CompanyProduct("Blend", "MS", "MS", "MSB")); companyProducts.Add(new CompanyProduct("MS Word", "MS", "MS", "MSO"));
Step 5:
Step 6:
Step 7:
radioButton.Name = list.Id;
Step 8:
Step 9:
Step 10:
Step 11:
Step 12:
private void radioButton_Checked(object sender, RoutedEventArgs routedEventArgs) { string selectedContent = (string)((RadioButton)sender).Content; RadioButton radioButton = ((RadioButton) sender); radioButton.IsEnabled = false; }
Step 13:
productStackPanel.Children.Add(radioButton);
Step 14:
this.LayoutRoot.Children.Add((productStackPanel));
Step 15:
Code Snippet:
namespace DynamicRadioButton { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); List<CompanyProduct> companyProducts = new List<CompanyProduct>(); companyProducts.Add(new CompanyProduct("Visual Studio", "MS", "MS", "MSVS")); companyProducts.Add(new CompanyProduct("SQl Server", "MS", "MS", "MSS")); companyProducts.Add(new CompanyProduct("Blend", "MS", "MS", "MSB")); companyProducts.Add(new CompanyProduct("MS Word", "MS", "MS", "MSO")); StackPanel productStackPanel = new StackPanel(); foreach (var list in companyProducts) { RadioButton radioButton = new RadioButton(); radioButton.Name = list.Id; //Displaying Text radioButton.Content = list.Product; //You can only select only one from group. radioButton.GroupName = list.Group; //Dynamic way of setting margin. radioButton.Margin = new Thickness(10.0); radioButton.HorizontalAlignment = HorizontalAlignment.Left; //Setting event at runtime radioButton.Checked += new RoutedEventHandler(radioButton_Checked); productStackPanel.Children.Add(radioButton); } this.LayoutRoot.Children.Add((productStackPanel)); } private void radioButton_Checked(object sender, RoutedEventArgs routedEventArgs) { string selectedContent = (string)((RadioButton)sender).Content; RadioButton radioButton = ((RadioButton) sender); radioButton.IsEnabled = false; } }
Step 16:
Step 17: