Osc*_*teu 7 wpf mvvm delegatecommand icommand
当我按下按钮时,我正试图获得两个Texbox的值(我正在模拟一个登录窗口).按钮中指定的命令正确触发,但我不知道如何获取文本框的值来执行"登录".
这是我的ViewModel:
class LoginViewModel : BaseViewModel
{
public LoginViewModel()
{
}
private DelegateCommand loginCommand;
public ICommand LoginCommand
{
get
{
if (loginCommand == null)
loginCommand = new DelegateCommand(new Action(LoginExecuted),
new Func<bool>(LoginCanExecute));
return loginCommand;
}
}
public bool LoginCanExecute()
{
//Basic strings validation...
return true;
}
public void LoginExecuted()
{
//Do the validation with the Database.
System.Windows.MessageBox.Show("OK");
}
}
Run Code Online (Sandbox Code Playgroud)
这是观点:
<Grid DataContext="{StaticResource LoginViewModel}">
<TextBox x:Name="LoginTxtBox" HorizontalAlignment="Left" Height="23" Margin="34,62,0,0" Width="154" />
<PasswordBox x:Name="PasswordTxtBox" HorizontalAlignment="Left" Height="23" Margin="34,104,0,0" Width="154"/>
<Button x:Name="btnAccept"
HorizontalAlignment="Left"
Margin="34,153,0,0"
Width="108"
Content="{DynamicResource acceptBtn}" Height="31" BorderThickness="3"
Command="{Binding LoginCommand}"/>
Run Code Online (Sandbox Code Playgroud)
如果有人能帮忙......我将无限感激.
Ree*_*sey 14
通常,您将TextBox.Text
属性绑定到ViewModel上的属性.这样,值存储在ViewModel中,而不是View中,并且没有"获取"所需的值.
class LoginViewModel : BaseViewModel
{
//...
private string userName;
public string UserName
{
get { return this.userName; }
set
{
// Implement with property changed handling for INotifyPropertyChanged
if (!string.Equals(this.userName, value))
{
this.userName = value;
this.RaisePropertyChanged(); // Method to raise the PropertyChanged event in your BaseViewModel class...
}
}
}
// Same for Password...
Run Code Online (Sandbox Code Playgroud)
然后,在你的XAML中,你会做类似的事情:
<TextBox Text="{Binding UserName}" HorizontalAlignment="Left" Height="23" Margin="34,62,0,0" Width="154" />
<PasswordBox Text="{Binding Password}" HorizontalAlignment="Left" Height="23" Margin="34,104,0,0" Width="154"/>
Run Code Online (Sandbox Code Playgroud)
此时,LoginCommand
可以直接使用本地属性.
归档时间: |
|
查看次数: |
26902 次 |
最近记录: |