views:

310

answers:

1

In WPF, I have a ListBox with a UserControl as its ItemTemplate - all data shown ok. I have now added a text box for input in that user control. In an MVVM design, I want to take some action (re-calculate values) in the main window when the user edits the content of the text box in the user control, in the item template, in the list box. Question is - how to propagate that event up to the model? The user control is bound to a business object and I can see the value being changed there ok (INotifyPropertyChanged is implemented in the BO), but, how to get that event up to the model (as opposed to the code-behind)? Any examples or pointers most welcome!

jas

A: 

I'm assuming, given that this is an MVVM application, that you are trying to propogate the text changed event up to the ViewModel.

You can do this without adding code behind in the View by using an Attached Property or a Behavior. There is actually a Behavior on the Expression Gallery that Invokes a command when you hit Enter in a TextBox. This could easily be reworked to fire a custom ICommand on your ViewModel whenever the TextBox changes its value (it's very similar in goals).

Reed Copsey
Thanks for pointing to me to these hitherto unexplored areas. Supposing I was to implement a behavior with an ICommand in the user control (in the item template, in the list box), I don't quite see how this would be actionable at the top level, where the list box is sited. Or, maybe my listbox/itemtemplate/usercontrol/textbox hierarchy is flawed? Thanks for the links - some more hits please would be useful. The example at the foll link is useful too, and behaviors seems to be the right idea (see http://codeblitz.wordpress.com/2009/07/01/wpf-editable-behavior-for-labels/)
jas
This lets you, potentially, bind your text changing to a command in the ViewModel, which lets you set properties or raise events that can propogate up the chain. In addition, after re-reading this, I realized you might want to use a Routed Event to propogate the event from your UserControl up to your higher level interfaces, which in turn can handle them any way they want. (They let you propogate up any number of "levels" in the visual tree...)
Reed Copsey
As it turned out, I achieved what I wanted with a simple dependency property. En route, I had two problems: the DP had not been two way and I did not have the binding syntax correct (what worked: "{Binding Path=DataContext.MyValue, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}, UpdateSourceTrigger=PropertyChanged}" ). Thanks for suggestions.
jas