views:

65

answers:

3

I have a simple property on my view model that is of type string. I want to bind this to a textbox so that changing the textbox updates the string and changing the string updates the textbox. Do I REALLY have a write a wrapper class around the string type that implements INotifyPropertyChanged, or am I missing something incredibly simple here?

+1  A: 

It's really easy to implement INotifyPropertyChanged. But what I would do, ViewModel classes almost always (if not always) inherit from DependencyObject; I would do this text property a DependencyProperty, which automatically notifies changes to whatever it's bound to. You can use the propdp shortcut in C# (in visual studio 2008, not sure if 2005 too) to create a DependencyProperty faster, just type propdp and hit the Tab key twice. It would look something like this:

 public string SomeText
 {
  get { return (string)GetValue(SomeTextProperty); }
  set { SetValue(SomeTextProperty, value); }
 }

 // Using a DependencyProperty as the backing store for SomeText.  This enables animation, styling, binding, etc...
 public static readonly DependencyProperty SomeTextProperty =
  DependencyProperty.Register("SomeText", typeof(string), typeof(YourClassName), new UIPropertyMetadata(String.Empty));
Carlo
Aren't we making our ViewModel classes heavy by deriving it from dependency object?
Trainee4Life
Probably, but with benefits. I don't have the facts to tell you exactly they should always derive from DependencyObject, but I've read about it in many articles and heard in many videos, here for instance blog.lab49.com/archives/2650 Jason Dolinger Intro to the MVVM pattern. It sounds right to me though, because the VM class will be controlling all the aspects of the window (state, animations, binding).
Carlo
I too watched the JD intro to MVVM and found it to be the most informative screencast I've seen to date on WPF. That's the only reason I'm even working with the MVVM pattern right now instead of attacking the program using an inline winforms style of coding. I'm not sure what weight dependency object brings with it, but it seems a fairly natural base class, given what the purpose the view model is supposed to serve.
Chris
+1  A: 

Use a DependencyProperty.

Taylor Leese
I gave Carlo the answer because he was slightly more verbose, but rated yours up too. Thanks!
Chris
+2  A: 

Actually you won't have to make a wrapper class around string type. INotifyPropertyChanged is to be implemented for every ViewModel class. This interface is required to send notification to the binding framework about changed data.

I would recommend visiting http://mvvmfoundation.codeplex.com/ and incorporating the MVVM foundation classes in your WPF project. The MVVM foundation provides a basic set of reusable classes that everyone should use. Although there are other extensive WPF frameworks like Cinch, Onyx etc., you could use.

Trainee4Life