wpf数据绑定 - 用字符串双向绑定?

时间:2009-09-30 18:17:41

标签: .net wpf data-binding

我的视图模型上有一个类型为string的简单属性。我想将其绑定到文本框,以便更改文本框更新字符串并更改字符串更新文本框。我是否真的在实现INotifyPropertyChanged的字符串类型周围编写了一个包装类,或者我在这里错过了一些非常简单的东西?

3 个答案:

答案 0 :(得分:2)

实现INotifyPropertyChanged非常简单。但是我会做什么,ViewModel类几乎总是(如果不是总是)继承自DependencyObject;我会将此文本属性设为DependencyProperty,它会自动将更改通知给它所绑定的任何内容。您可以使用C#中的propdp快捷方式(在visual studio 2008中,不确定是否也是2005)来更快地创建DependencyProperty,只需键入propdp并按两次Tab键。它看起来像这样:

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

答案 1 :(得分:2)

实际上你不必围绕字符串类型创建一个包装类。将为每个ViewModel类实现INotifyPropertyChanged。需要此接口才能向绑定框架发送有关已更改数据的通知。

我建议访问http://mvvmfoundation.codeplex.com/并将MVVM基础类合并到WPF项目中。 MVVM基础提供了一组基本的可重用类,每个人都应该使用它们。虽然还有其他广泛的WPF框架,如Cinch,Onyx等,但您可以使用。

答案 2 :(得分:1)

相关问题