MVVM Light Binding

时间:2015-02-10 16:54:45

标签: binding mvvm-light inotifypropertychanged

我正在研究WPF项目并使用MVVM灯。文本框绑定似乎不起作用。你知道为什么吗?我通过MVVM光框架中实现的ViewModelBase类使用INotifyPorpertyChanged实现。

我有2个文本框用户名和密码...我希望当用户在两个文本字段中输入字符时,链接到这些控件的属性会更改其值。

谢谢。

视图模型

  #region Helpers Properties

        private UserBLL UserBLLManager;
        public UserBO User;
        public RelayCommand AddNewUserCommand { get; private set; }
        public RelayCommand TryToLoginCommand { get; private set; }

        #endregion

        public MainViewModel()
        {
            if (UserBLLManager == null)//service
                UserBLLManager = new UserBLL();

            if (User == null)//model
                User = new UserBO();

            AddNewUserCommand = new RelayCommand(() => AddNewUser());
            TryToLoginCommand = new RelayCommand(() => TryToLogin());
        }


            public void AddNewUser()
            {
                 //do stuff

            }

        }
    }

模型

public class UserBO:ObservableObject
        {   
            private string username;
            public string Username
            {
                get { return username; }
                set
                {
                    if (value != username)
                    {
                        username = value;
                        RaisePropertyChanged("Username");
                    }
                }
            }

            private string password;
            public string Password
            {
                get { return password; }
                set
                {
                    if (value != password)
                    {
                        password = value;
                        RaisePropertyChanged("Password");
                    }
                }
            }   
        }

的ServiceLocator

  
    public class ViewModelLocator
    {

        public ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);


            SimpleIoc.Default.Register<MainViewModel>();

        }

        public MainViewModel Main
        {
            get
            {
                return ServiceLocator.Current.GetInstance<MainViewModel>();
            }
        }

        public static void Cleanup()
        {
            // TODO Clear the ViewModels
        }
}

查看

    <Window x:Class="MyCook.MainView"
                DataContext="{Binding Main, Source={StaticResource Locator}}">

            <Grid>

                        <TextBox Name="Username_TxtBox" Text="{Binding User.Username,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></TextBox>

                        <TextBox Name="Pwd_TxtBox" Text="{Binding User.Password,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" ></TextBox>

</Grid>

1 个答案:

答案 0 :(得分:1)

1)用户应该是公开的。绑定到私人财产毫无意义。

2)如果您希望在用户输入值后更改基础属性,则必须将绑定设置为TwoWay:

Text="{Binding User.Username,Mode=TwoWay}"

3)实体类不应来自ViewModelBase。而是转到ObservableObject