views:

364

answers:

5

I'm using PRISM (and thus the MVVM pattern). I've got a complex DateTime picker view with radio buttons. The user can pick today, yesterday, a date, a week of a year, etc. I use radio buttons for the different choices.

What's the best way to do that in MVVM? I really can't think of a clean way. I could create lots of custom behaviors to add to each item to track them but it doesn't seem maintainable.

I'm going to put some code-behind but I really don;t like that and to me it breaks the MVVM principle (put everything in the XAML).

Does anyone have a better idea on how to go about that?

A: 

How about a ComboBox instead of the RadioButtons presenting a list of TimeOffset (custom class) bound to your ViewModel, with a corresponding SelectedTimeOffest property.
If you need to display extra information depending on the type of TimeOffset, e.g. a WeekOffset (subclass of TimeOfset) with a WeekCount property, have a content control with several DataTemplates customized by the type of TimeOFfset.

Just an idea...

Julien Poulin
A: 

The ViewModel is designed to present the model in a way the view can consume.

In this case, you could have a boolean property for each button in the VM, and when a button updates it just sets all the other properties to false. Then in your View you can bind each properties IsChecked to the corresponding property in the ViewModel.

Also, be aware there is currently a bug in binding radio buttons in WPF. Here's a potential solution.

Cameron MacFarland
Wow, I posted that bug ages ago and I didn't realize it got so much attention ;) Note that its fixed in .NET 4 though.
James Cadd
@JC So you're responsible! :P
Cameron MacFarland
+1  A: 

Keep the RadioButtons, add an enum type to your VM that can return things like "Today" "Yesterday" or "Tomorrow." On the UI side create a ValueConverter that takes a parameter like "Tomorrow" and compares it with the bound value on VM, then returns the bool? needed by IsChecked.

James Cadd
A: 

Put it in code behind.

The M-V-VM pattern is not "put everything in xaml" it's "separate concerns". Your VM wants a DateTime right? In which case it doesn't care how that DateTime is being chosen it just needs a DateTime.

Putting View logic in the ViewModel isn't a good idea as you're now giving the VM knowledge about the workings of the View. The flow is meant to be View knows about the ViewModel which knows about the Model. The reverse is not normally true. (As with all things computer related there is always exceptions)

Hope this helps.

Graeme Bradbury
A: 

you could create a enum, bind the values of the enum to a listbox, retemplate the ListboxItems this post is using silverlight, but something similar should work http://leeontech.wordpress.com/2009/03/18/creating-radiobuttonlist/