I used the following code to add a BusyIndicator dynamically to a ChildWindow in a Silverlight 4 application, I made it according to the following premises:
1. If it's a ChildWindow the Content property should be setted to a Grid.
2. If it's a Silverlight Page the Content property could be a ScrollViewer or a Grid.
After this, I created a static class name Utilities in which I wrote the following code:
- public static void SetBusyState(Object Content, bool IsBusy)
- {
- Grid pageGrid = null; //a variable to handle the page/Window main Grid
- BusyIndicator _indicator = null; //the busyIndicator content (Silverlight 4 SDK)
- try
- {
- pageGrid = (Grid)Content; //tries to parse the content into a Grid
- }
- catch //If an exception is thrown (is not a grid)
- {
- try
- {
- pageGrid = ((Grid)((ScrollViewer)Content).Content); //we look if it's a ScrollViewer
- }
- catch //If an exception is Thrown (content is not a ScrollViewer)
- {
- pageGrid = null; //if not the control is set to null (you can try to parse another
- //type)
- }
- }
- if (pageGrid != null) //if the above code found the Grid
- {
- try
- {
- foreach (UIElement p in pageGrid.Children) //Now we interate the Grid Children until
- {
- try
- {
- _indicator = (BusyIndicator)p; //the busyIndicator is found
- if (_indicator != null && IsBusy)//if we find it (and we want to set it to busy)
- {
- //set the busyIndicator to Busy (with a default message stored on the App resources).
- _indicator.BusyContent = ApplicationStrings.PleaseWaitMessage;
- _indicator.IsBusy = IsBusy;
- }
- else if (_indicator != null && !IsBusy) //if we find it but is set to false
- {
- pageGrid.Children.Remove(_indicator); //just remove it from the Grid
- }
- }
- catch
- {
- continue; //continues the cycle after every exception (control not found)
- }
- }
- if (_indicator == null && IsBusy) //if the control is not added to the page/window
- {
- _indicator = new BusyIndicator(); //creates a new BusyIndicator
- _indicator.Margin = new Thickness(0, 0, 0, 0); //Set its position
- _indicator.Width = pageGrid.Width; //Set its widht as the same as Grid
- _indicator.Height = pageGrid.Height; //Set its height as the same as Grid
- _indicator.BusyContent = ApplicationStrings.PleaseWaitMessage; //The Message
- _indicator.IsBusy = IsBusy; //Set it to busy
- pageGrid.Children.Add(_indicator); //Adds the control the Grid
- }
- }
- catch
- {
- Ocupado(Content, IsBusy);//this line here helps you when the Content state is not valid
- //generally happens when a IvalidOperationException is thron, so we call the method
- //until the state is valid
- }
- }
- }
To use the SetBusyState function you just have to call it by passing the Page/Window Content property and the value you want to set to the BusyIndicator.
This is working for me right now, but I will also accept recommendations.
Regards,
José