tags:

views:

56

answers:

1

I have 18 Buttons within a Uniform grid on my main WPF window. I need to modify many of the Button's Properties and Command both when the program loads and during operation. In other words, when the program first starts, a configuration is selected that affects the layout. Later that could change further depending on how the program operates. I'm trying to consolidate all logic within a ViewModel. So the simple question is - how to best implement this design?

A few ideas:

  • Could use traditional bindings. This works except you could end up with 100's of them. Also, would have ugly logic within each property - i.e. if config1 then background is red, else if config2 or 3 then background is blue.

  • Could limit the number of bindings with ValueConverters and CommandParameters but then you have even messier property logic.

  • Could bind to the Button's style. This works to simplify the property settings but you end up with a bunch of styles to mess with. Also doesn't work well after the program is loaded (I don't think you can change a Style after it's applied).

  • Could have a different Uniform grid (each with a set of 18 buttons) for each configuration, then only show the selected one. This simplifies the property logic but messes up the XAML.

  • Could pass the Button objects themselves to the ViewModel. Not sure how to implement this plus I think it breaks the MVVM pattern. Might be the easiest if I knew how to do it.

I'm at a loss for an elegant solution. I'm sure there is something simple I'm missing. Any ideas are appreciated. Thanks.

A: 

Here is what I have done in that case:

Since you have several properties you want to bind to on each button, including a command, I would make a separate, small ViewModel (MyButtonViewModel) for each button, which includes the properties and command.

Then, in the primary ViewModel, I would create a collection (ObservableCollection<MyButtonViewModel>) of your button view models, and populate it using some simple looping (or LINQ) code.

Then, in the View, I would declare an ItemsControl to use an ItemPanel of UniformGrid. Then, For the ItemTemplate, I'd define the button to bind to the properties in MyButtonViewModel.

Simple, small, and elegant IMO.

Let me know if you need any clarification, B

Brian Genisio
Interesting concept. Thanks for the input. I appreciate the help. I'll work on the idea and let you know how it turns out.
rastro
That worked great! Thanks for the ideas.
rastro