Silverlight async calls and anonymous methods....

Posted by JLewis on Stack Overflow See other posts from Stack Overflow or by JLewis
Published on 2009-05-07T18:27:14Z Indexed on 2010/03/19 19:01 UTC
Read the original article Hit count: 674

I know there are a couple of debates on this kind of thing.... At any rate, I have several cases where I need to populate combobox items based on enumerations returned from the WCF service.

In an effort to keep code clean, I started this approach. After looking into it more, I don't think the this works as well is initially thought...

I am throwing this out to get recommendations/advice/code snippets on how you would do this or how you currently do this.

I may be forced to have a seperate, non anonymous method, procedure. I hate doing this for something like this but at the moment, don't see it working another way...

EventHandler<GetEnumerationsForTypeCompletedEventArgs> ev = null;
                ev = delegate(object eventSender, GetEnumerationsForTypeCompletedEventArgs eventArgs)
                    {
                        if (eventArgs.Error == null)
                        {
                            //comboBox.ItemsSource = eventArgs.Result;
                            // populate combox for display purposes (for now)
                            foreach (Enumeration e in eventArgs.Result)
                            {
                                ComboBoxItem cbi = new ComboBoxItem();
                                cbi.Content = e.EnumerationValueDisplayed;
                                comboBox.Items.Add(cbi);
                            }
                            // remove event so we don't keep adding new events each time we need an enumeration
                            proxy.GetEnumerationsForTypeCompleted -= ev;
                        }
                    };
                proxy.GetEnumerationsForTypeCompleted += ev;
                proxy.GetEnumerationsForTypeAsync(sEnumerationType);

Basically in this example we use ev to hold the anonymous method so we can then use ev from within the method to remove it from the events once called. This prevents this method from getting called more than one time.

I suspect that the comboBox local var declared before this call, but within the same method, is not always the combobox originally intended but can't really verify that yet. I may add a tag to it to do some tests and populating to verify.

Sorry if this is not clear. I can elaborate more if needed.

Thanks Jeff

© Stack Overflow or respective owner

Related posts about Silverlight

Related posts about asynchronous