如何使用MVVM正确绑定我的文本框

时间:2015-03-18 15:45:18

标签: c# wpf xaml mvvm

我正在将我的项目转移到MVVM模式,但绑定不起作用。以下是我的项目代码。问题是当在LRViewModel.cs中创建新对象时,文本框不会更新值,但消息框会弹出窗口,指定该属性已更改,但不会更新文本框。

LoginRegister.xaml.cs:

using CSMS_MVVM.ViewModels;
private LrViewModel _lrViewModel;
public LoginRegister()
        {
            InitializeComponent();
        }
private void Page_Loaded_1(object sender, RoutedEventArgs e)
        {
            _lrViewModel = new LrViewModel();
            this.DataContext = _lrViewModel;
        }

LoginRegister.xaml

.
.
.
<TextBox Name="regID" Text="{Binding RegId,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Padding="8" Margin="15,110,20,0" VerticalAlignment="Top" BorderBrush="#FFD4F1FF" FontSize="15" ToolTip="Username or Employee ID" FontFamily="Calibri" />
.
.
.

LRViewModel.cs

using CSMS_MVVM.Models;

namespace CSMS_MVVM.ViewModels
{
    class LrViewModel
    {
        public LrModel LrModel { get; set; }

        public LrViewModel()
        {
            LrModel=new LrModel
            {
                RegId = "Value"
            };
        }
    }
}

LrModel.cs

namespace CSMS_MVVM.Models
{
    class LrModel : INotifyPropertyChanged
    {
        private String _regId;

        public String RegId
        {
            get { return _regId; }
            set
            {
                _regId = value;
                OnPropertyChanged(new PropertyChangedEventArgs("RegId"));
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(PropertyChangedEventArgs propertyChangedEventArgs)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, propertyChangedEventArgs);
            MessageBox.Show("Here");
        }

        #endregion

    }
}

1 个答案:

答案 0 :(得分:2)

你应该改变这个..

<TextBox Name="regID" Text="{Binding LrModel.RegId,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Padding="8" Margin="15,110,20,0" VerticalAlignment="Top" BorderBrush="#FFD4F1FF" FontSize="15" ToolTip="Username or Employee ID" FontFamily="Calibri" />

因为要绑定的属性实际上是模型的属性,而model是视图模型的属性..您应该绑定到Model.PropertyName ..并且当model.Property触发其属性更改时...用户界面将会更新。

- 建议 -

您不应该在后端C#代码中设置DataContext。相反,(在此方案中)您可以在XAML中设置DataContext

<Window
    xmlns:ViewModels="clr-namespace:TheNamespaceWhereYourViewModelIs"
    ...
    >
   <Window.DataContext>
      <ViewModels:YourViewModel/>
   </Window.DataContext>