views:

1382

answers:

1

I have a group of checkboxes that all represent different selections of the same type (for my example, they are all different file types). I feel like binding each one to an individual property in the ViewModel is overkill, and I'd prefer to bind them all to one collection and use the binding syntax to bind each checkbox to a particular item in the collection by key. I'm trying to stick to the MVVM pattern, so I don't just want to get lazy and handle the Checked event or something like that.

Is there a way to express a path or key within a collection using WPF binding syntax? For example, if I expose a Dictionary<string, bool> called FileTypes as a public property in the ViewModel, is there a way for me to bind one of the checkboxes to FileTypes["aspx"]? What if I had a more complex data structure like Dictionary<string, Dictionary<string, int>>?

+1  A: 

You almost had it -- just drop the quotes around the indexer argument:

{Binding FileTypes[aspx]}

A more complex data structure would just require a sequence of indexers, e.g.

{Binding Foo[aspx][Bar]}

By the way, a good resource for this stuff is in MSDN, under WPF > Data > Data Binding > Binding Declarations Overview -- scroll down to "Binding Path Syntax" for a summary of the notations and conventions you can use in a binding path.

itowlson