C# INotifyPropertyChanged on properties of a dynam

2019-07-15 12:13发布

(update) ICustomTypeDescriptor works for my Windows Forms app, but not for Silverlight; Not supported. I will keep investigating this idea though and see where i get to. (/update)

I have, say a few switch panels (for those that like analogies). Each of these switch panels has switches that have a Name(string) can be in state(bool) of On or Off. The switchpanel and switches are objects that have INotify interface on them.

Using the switches Names, I create a list of all possible switch names over the collection and create a dynamic class that has all these Names as properties.

SwitchPanel1 (Switches( Switch1 ("Main",On) , Switch2("Slave",Off)))
SwitchPanel2 (Switches( Switch1 ("Bilge",On) , Switch2("Main",Off)))

Produces a collection of

(Main,Bilge,Slave)

And a dynamic class is produced that has the properties:

SwitchPanel : (SwitchPanel)
Main : (Switch)
Bilge : (Switch)
Slave: (Switch)

The idea is that if the switch panel has a switch with the Name of the property, it is placed on that property. So using a bit of linq

propeties["Main"].SetValue(newSwitchType,SwitchPanel.Switches.FirstOrDefault(sw => sw.Name == "Main"));

I want to cast this new dynamic class to INotfyPropertyChanged AND catch the actual changes on these new properties, so if a switch changes state the dynamic object will report it.

Why? It needs to be displayed in a list view and the list view I'm using has its binding by supplying the Property name, and not the binding path.

It also attempts to catch INotify events by casting the object against INotifyPropertyChanged. This means it will sort and/or group when things change.

If you know of a better way to do this let me know. Please.

1条回答
贪生不怕死
2楼-- · 2019-07-15 12:43

You probably don't need a dynamic class. You can implement runtime binding properties via ICustomTypeDescriptor / GetProperties(), creating your own PropertyDescriptor implementation that returns the named switch. It isn't clear what knows first about the change, but you could either use INotifyPropertyChanged, or the older property-specific change event, again tied to each property (so each PropertyDescriptor attaches to, for example, the event in the named switch.

Not trivial, but not impossible either.

查看更多
登录 后发表回答