[英]Managing the IsEnabled property of a button
我的程序中有一個xaml窗口,它有一個名為“Save”的按鈕和一個textBox
。 我也有一個ViewModel用於此窗口。 在ViewModel中,我有一個textBox
的string
屬性,以及按鈕上的IsEnabled
的bool
屬性。 我希望只有當textBox
有文本時才啟用該按鈕。
XAML:
<Button IsEnabled="{Binding SaveEnabled}" ... />
<TextBox Text="{Binding Name}" ... />
ViewModel屬性:
//Property for Name
public string Name
{
get { return _name; }
set
{
_name = value;
NotifyPropertyChange(() => Name);
if (value == null)
{
_saveEnabled = false;
NotifyPropertyChange(() => SaveEnabled);
}
else
{
_saveEnabled = true;
NotifyPropertyChange(() => SaveEnabled);
}
}
}
//Prop for Save Button -- IsEnabled
public bool SaveEnabled
{
get { return _saveEnabled; }
set
{
_saveEnabled = value;
NotifyPropertyChange(() => SaveEnabled);
}
}
我認為我的主要問題是,我在哪里提出有關此問題的代碼? 正如您在上面所看到的,我已經嘗試將其放入Name
屬性的setter
中,但它沒有成功。
你可以這樣做:
public string Name
{
get { return _name; }
set
{
_name = value;
NotifyPropertyChanged(() => Name);
NotifyPropertyChanged(() => SaveEnabled);
}
}
public bool SaveEnabled
{
get { return !string.IsNullOrEmpty(_name); }
}
編輯:將此添加到您的xaml:
<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}">...</TextBox>
使用MVVM中使用的ICommands:
private ICommand _commandSave;
public ICommand CommandSave
{
get { return _commandSave ?? (_commandSave = new SimpleCommand<object, object>(CanSave, ExecuteSave)); }
}
private bool CanSave(object param)
{
return !string.IsNullOrEmpty(Name);
}
private void ExecuteSave(object param)
{
}
然后在XAML代碼中使用以下內容
<TextBox Command="{Binding CommandSave}" ... />
根據您使用的框架,命令類的工作方式不同。 對於通用實現,我建議使用Relay Command 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.