我正在使用MvvmLight编写演示程序。我想要的是将View
中的TextBox绑定到Model
中的属性。绑定似乎正确,因为我可以显示我的输入MessageBox的TextBox。问题是在ViewModel
中将属性设置为string.Empty后,View
中的文本框保持不变。
Model
LoginToMisInfo.cs
using GalaSoft.MvvmLight;
namespace MvvmLight1.Model
{
/// <summary>
/// This class contains properties that a View can data bind to.
/// <para>
/// See http://www.galasoft.ch/mvvm
/// </para>
/// </summary>
public class LoginToMisInfo : ViewModelBase
{
/// <summary>
/// Initializes a new instance of the LoginToMisInfo class.
/// </summary>
public LoginToMisInfo()
{
}
private string userName;
public string UserName
{
get
{
return userName;
}
set
{
userName = value;
}
}
}
}
ViewModel
LoginToMis.cs
using GalaSoft.MvvmLight;
using MvvmLight1.Model;
using System.ComponentModel;
using GalaSoft.MvvmLight.Command;
using System.Windows.Input;
using System.Windows;
namespace MvvmLight1.ViewModel
{
/// <summary>
/// This class contains properties that a View can data bind to.
/// <para>
/// See http://www.galasoft.ch/mvvm
/// </para>
/// </summary>
public class LoginToMis : ViewModelBase
{
/// <summary>
/// Initializes a new instance of the LoginToMis class.
/// </summary>
public LoginToMis()
{
//CommandCancel = new RelayCommand(() => ConfirmExecute(), () => true);
CommandConfirm = new RelayCommand(() => ConfirmExecute(), () => true);
CommandClear = new RelayCommand(() => ClearExecuate(), () => true);
}
LoginToMisInfo LoginInfo = new LoginToMisInfo();
public event PropertyChangedEventHandler PropertyChanged;
public string UserName
{
get
{
return LoginInfo.UserName;
}
set
{
LoginInfo.UserName = value;
if(this.PropertyChanged!=null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("LoginInfo.UserName"));
}
}
}
public ICommand CommandCancel { get; private set; }
public ICommand CommandConfirm { get; private set; }
public ICommand CommandClear { get; private set; }
private void ConfirmExecute()
{
MessageBox.Show(UserName);
}
private void ClearExecuate()
{
UserName = string.Empty;
}
}
}
View
:
DataContext
DataContext="{Binding MyLoginToMis, Source={StaticResource Locator}
(我已在LoginToMis
注册ViewModelLocator
)
TextBox
<TextBox Grid.Row="0" Grid.Column="1"
MinWidth="100"
Text="{Binding UserName,UpdateSourceTrigger=PropertyChanged}"/>
'按钮'
<Button Content="Confirm" MinWidth="150" MinHeight="80"
Margin="50,0,50,0" IsDefault="True"
Command="{Binding CommandConfirm}"/>
<Button Content="Clear" MinWidth="150" MinHeight="80"
Margin="50,0,50,0" Command="{Binding CommandClear}"/>
基本上,我在Model
中创建了一个类,并在ViewModel
中包装了它的一个实例,然后我将ViewModel
中的属性绑定到View
中的TextBox中{1}}。在TextBox中输入一些单词并单击确认后,将弹出一个MessageBox并在TextBox中显示输入。单击清除,然后单击TextBox不要更新。任何想法?
答案 0 :(得分:3)
您应该为UserName
属性提高属性更改通知。
您可以使用RaisePropertyChanged
提供的MvvmLight
方法提出属性更改通知。 ViewModelBase
类提供的方法,该方法继承ObservableObject
:
RaisePropertyChanged("UserName");