tags:

views:

204

answers:

2

I have a Silverlight 3 application, and it has radiobuttons grouped using the GroupName property. What I would like to do in the code is retrieve all the radiobuttons that are part of a specified group. Is there an easy way to do this, or would I need to iterate over all the controls?

Thanks.

A: 

This might help: Essentially walk through the controls looking for radiobuttons in the required group. This will also look through any children panels.

private List<FrameworkElement> FindBindings(DependencyObject visual, string group)
{
    var results = new List<FrameworkElement>();

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(visual); i++)
    {
        var childVisual = VisualTreeHelper.GetChild(visual, i);
        var childRadioButton = childVisual as RadioButton;
        if (childRadioButton != null)
        {
            if (childRadioButton.GroupName == group)
            {
                results.Add(childRadioButton);
            }
        }
        else
        {
            if (childVisual is Panel)
            {
                results.AddRange(FindBindings(childVisual, group));
            }
        }
    }
    return results;
}
Stephen Price
+3  A: 

Borrowing (yet again) my VisualTreeEnumeration from this answer (I really really need to blog):-

public static class VisualTreeEnumeration 
{ 
   public static IEnumerable<DependencyObject> Descendents(this DependencyObject root) 
   { 
     int count = VisualTreeHelper.GetChildrenCount(root); 
     for (int i=0; i < count; i++) 
     { 
       var child = VisualTreeHelper.GetChild(root, i); 
       yield return child; 
       foreach (var descendent in Descendents(child)) 
         yield return descendent; 
     } 
   } 
} 

Place this in a file in either your main namespace or in a utility namespace that you place a using for in your code.

Now you can use LINQ to get all sorts of useful lists. In your case:-

 List<RadioButton> group = this.Descendents()
                               .OfType<RadioButton>()
                               .Where(r => r.GroupName == "MyGroupName")
                               .ToList();
AnthonyWJones