Chris
Chris

Reputation: 28064

wpf databinding - two way binding with a string?

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?

Upvotes: 1

Views: 879

Answers (3)

Trainee4Life
Trainee4Life

Reputation: 2273

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.

Upvotes: 2

Taylor Leese
Taylor Leese

Reputation: 52390

Use a DependencyProperty.

Upvotes: 1

Carlo
Carlo

Reputation: 25969

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));

Upvotes: 2

Related Questions