Sunday, January 13, 2013

referring c# instance of object variable name with a string

referring c# instance of object variable name with a string

In Windows 7 phone (Silverlight platform), when a ListBox is created, the name of that ListBox is instatiated and assigned to a variable of the same name:

<ListBox Name="abcFeed" ... 

and used as:

abcFeed.ItemsSource = feed.Items; 

In my app I have many feeds and want to assign them to their respective ListBoxes. I have the names of the list boxes in a dictionary of strings.

this.feeds["abcFeed"] = "http://feed.abc.com/...."; this.feeds["nbcFeed"] = "http://feed.nbc.com/...."; 

But other than using a switch to assign the feeds to the ListBoxes I was wanting to take the ListBox string names from my dictionary and in a loop dynamically call the instances.

For example instead of doing:

feedName = "nbcFeed"; // Bind the list of SyndicationItems to our ListBox. switch (feedName) {   case "abcFeed":     abcFeed.ItemsSource = feed.Items;     break;   case "nbcFeed":     nbcFeed.ItemsSource = feed.Items;     break; } 

I would like to somehow take the dictionary keys and call the instantiated variablename like:

feedName = "nbcFeed"; // nbcFeed.ItemsSource = feed.Items; ((ListBox) feedName).ItemsSource = feed.Items; 

I've looked into Reflection, Assembly, and Activator.CreateInstance() (I already hve the instance though) but Im not getting a clear understanding if this is possible.

Can this be done or am I stuck with the switch?

I also tried:

this.GetType().GetProperty(feedName).ItemsSource = feed.Items; 

but I get an error:

Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type

Answers & Comments...

Answer: 1

Yes, Reflection is what you need to do this. But this:

this.GetType().GetProperty(feedName).ItemsSource = feed.Items;

doesn't work because Type.GetProperty() method returns a PropertyInfo (as Type.GetMethod() returns MethodInfo and so on...) so you should use PropertyInfo.GetValue() or PropertyInfo.SetValue() method if you want to work on the property value.

In your case this could work:

var myProperty = (ItemsControl)GetType().GetProperty(feedName).GetValue(this, null);  myProperty.ItemsSource = feed.Items; 
by : Fuexhttp://stackoverflow.com/users/1141063

Answer: 2

Unfortunately, you cannot access fields defined in XAML using reflection. Security restrictions in Silverlight prevent access to NonPublic fields (such as those generated for your XAML elements).

Using FindName should work fine.

ListBox abcFeed = LayoutRoot.FindName("abcFeed") as ListBox; 
by : TriggerPinhttp://stackoverflow.com/users/1549726




20 comments:

Anonymous said...

Now, once its start thawing put 1 quart of soda
in it. When reading a Breville blender review, or any review for example, you need to keep in mind exactly what purpose you happen to be going to make
use of the item for. With simple hand blenders, you'll be able to easily prepare food in a very matter of minutes without the headache of complicated clean ups after.

my web blog: hand blender

Anonymous said...

Woah! I'm really enjoying the template/theme of this blog. It's simple, yet effective.
A lot of times it's difficult to get that "perfect balance" between user friendliness and visual appeal. I must say you have done a superb job with this. In addition, the blog loads extremely fast for me on Internet explorer. Exceptional Blog!

My page ... church sound systems

Anonymous said...

At thiѕ time it sounds liκе ΒlogEngine is the best bloggіng ρlatform оut theге гight now.
(fгom whаt I've read) Is that what you are using on your blog?

Feel free to surf to my webpage: sciatica nerve pain

Anonymous said...

Hі there! Do you use Tωіttеr?
I'd like to follow you if that would be okay. I'm definіtеlу enjоying your
blog anԁ look foгwагd to new postѕ.


Αlso visit mу websitе; surveillance Camera

Anonymous said...

Hi there! Ӏ just ωanted to ask if you evег
have any іssues with hackеrs? My lаst blog (wordprеѕs) ωas hackеd and I ended up losіng ѕeveгal ωеekѕ of hаrd work due to
no data bаckup. Do уou hаve any solutіons to ѕtop hackers?


Μy ѕite :: best home surveillance system

Anonymous said...

Hі! Thіѕ post could nоt be written any better!

Rеading thіs pоst reminԁs me of my
good old room mate! Нe аlwаyѕ kept chatting about
this. I will foгωard thiѕ post to hіm.
Fairly certаіn he will have a gooԁ rеad.
Thаnκ уou for ѕharing!

Fеel freе to vіsit my blog; portable sound system **

Anonymous said...

Thank you, I have recently been searching for info about this subject for a long time and yours is the best I've discovered till now. However, what concerning the conclusion? Are you certain about the source?

my web site; 5 year anniversary

Anonymous said...

I simply сould not gο аway your
website before suggesting that I extremеlу еnјoуеd the ѕtandагd infο
a person supplу in уouг guestѕ?
Ιs gοing to bе back frequently in order to chеck out new postѕ

Αlso visit my ωеbρage; pa system packages

Anonymous said...

I'm truly enjoying the design and layout of your website. It's
a νeгy easy on thе eyes whiсh makes it much more ρlеаsant for me to come here
and visit morе often. Diԁ you hirе оut а dеvеloрer to create your theme?
Εxcellent work!

Have a look at my blog роѕt: hybrid sound system ()

Anonymous said...

Outstanding post howеѵer , I ωas ωοndering if you coulԁ write а lіtte mοre on this topiс?
I'd be very thankful if you could elaborate a little bit further. Appreciate it!

my homepage acupuncture for weight loss

Anonymous said...

Hi! I just wanted to ask if you ever have
any problems with hackers? My last blog (wordpress) was
hacked and I ended up losing a few months of hard work due to no back
up. Do you have any methods to protect against hackers?


Here is my homepage sound equipment online **

Anonymous said...

Wonderful blog! I found it while surfing around on Yahoo News.
Do you have any suggestions on how to get listed in Yahoo News?

I've been trying for a while but I never seem to get there! Thank you

Look at my web blog :: audio technica 2000

Anonymous said...

Whats up this is kind of of off topic but I was
wondering if blogs use WYSIWYG editors or if you have to manually code with HTML.
I'm starting a blog soon but have no coding skills so I wanted to get guidance from someone with experience. Any help would be greatly appreciated!

my weblog ... some green screen studio magic

Anonymous said...

Hey would you mind letting me know which web host you're working with? I've loaded your blog in 3 completely
different internet browsers and I must say this blog loads a lot quicker then most.
Can you suggest a good internet hosting provider at a fair price?
Thank you, I appreciate it!

Here is my web site: pre k ()

Anonymous said...

Gгeetіngs! I know this is κinda off topic but І'd figured I'd ask.
Would уou be inteгeѕted іn exchanging links or mаybе guest authoring a blog article oг ѵice-versa?
My webѕite goes over а lot οf the ѕame subjects as yours аnd I feel we could greatly benefit from еаch othеr.
If you happen to be interested feel freе to shoot me an e-maіl.
I lοok forwarԁ to hеаring from yοu!
Wonԁеrful blog by thе waу!

Feel free to visit my site; audio 2000

Anonymous said...

What's up i am kavin, its my first occasion to commenting anyplace, when i read this paragraph i thought i could also make comment due to this good piece of writing.

Feel free to visit my web-site: anniversary gifts for parents (agenwisata.net)

Anonymous said...

What's up friends, good post and good arguments commented here, I am genuinely enjoying by these.

my homepage first anniversary gifts

Anonymous said...

Fine written. I learned a lot, post even more in the
future. Carry on the good work.

My weblog: what is a dos attack (http://ssmethai.org/)

Anonymous said...

They'll most probably and honest about the fact that they're paying you for
that metal content (weight) of the items, and should educate you about any
aesthetic or artistic value your piece may have that could potentially exceed the
metal value. Often times it really is seen that using the
stainless-steel flatware to eat something sour
will destroy the shine of your metal flatware so you often
try home tips to give them the shine they once had. The smooth and shiny appearance of flatware
stainless brings beauty towards the dining tables.

Look into my web-site ... flatware - -

Anonymous said...

a young child can chat with his best friend during the sided of your day without having so you can leave the house.
There can be often simple precautions you can take to make yourself less of a desired.
One last thing, when talking with a kid on anything serious, get down to
their level.

Also visit my blog post - walkie talkies for kids uk - -

Post a Comment

Send us your comment related to the topic mentioned on the blog