我在视图中遇到错误处理问题。我使用caliburn.micro和MEF。
我的VM看起来像这样:
[Export(typeof(IShellViewModel))]
public class ShellViewModel : PropertyChangedBase, IShellViewModel,IDataErrorInfo
{
#region Private members
private User _user;
private Dictionary<string, bool> _validProperties;
private bool _allPropertiesValid;
#endregion
#region Private methods
private void ValidateProperties()
{
if (_validProperties.Values.Any(isValid => !isValid))
{
AllPropertiesValid = false;
return;
}
AllPropertiesValid = true;
}
#endregion
#region Constructor
public ShellViewModel()
{
_user = new User();
_validProperties = new Dictionary<string, bool> {{"Nick", false}, {"Password", false}};
}
#endregion
#region Properties
public bool AllPropertiesValid
{
get { return _allPropertiesValid; }
set
{
if (_allPropertiesValid != value)
{
_allPropertiesValid = value;
NotifyOfPropertyChange("AllPropertiesValid");
}
}
}
#endregion
#region Implementation of IShellViewModel
public string Nick
{
get { return _user.Nick; }
set
{
_user.Nick = value;
NotifyOfPropertyChange("Nick");
}
}
public string Password
{
get { return _user.Password; }
set
{
_user.Password = value;
NotifyOfPropertyChange("Password");
}
}
public void EmptyLogOn()
{
MessageBox.Show(string.Format("LogOn on server with credential: {0}, {1}", Nick, Password));
}
public void LogOn(string nick, string password)
{
MessageBox.Show(string.Format("LogOn on server with credential: {0}, {1}", nick, password));
}
#endregion
#region Implementation of IDataErrorInfo
public string Error
{
get { return (_user as IDataErrorInfo).Error; }
}
public string this[string propertyName]
{
get
{
string error = (_user as IDataErrorInfo)[propertyName];
_validProperties[propertyName] = String.IsNullOrEmpty(error) ? true : false;
ValidateProperties();
CommandManager.InvalidateRequerySuggested();
return error;
}
}
#endregion
}
如果我有som错误,我将属性AllPropertiesValid设置为false。我在Button属性IsEnabled上绑定了这个属性。
所以在View中我有这个:
<Button IsEnabled="{Binding AllPropertiesValid, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
Micro:Message.Attach="EmptyLogOn"
Content="Prihlás ma"
Width="100"
Height="25"
VerticalAlignment="Center"
Grid.Row="2"
Grid.ColumnSpan="2"></Button>
<Label Content="{Binding AllPropertiesValid}" Grid.Row="3"/>
但是如果属性AllPropertiesValid为false,则仍然启用Button。我检查AllPropertiesValid的值(我在标签上绑定此属性,标签内容为false)为false。
怎么了?感谢提前。
编辑:在设计器中禁用按钮,但是加载时窗口按钮启用。
答案 0 :(得分:1)
如果您正在执行 MVVM ,那么您应该使用ICommand
(或其他更高级别的变体,例如CommandBase
,...),因为您需要执行某些操作单击按钮时。
在这种情况下,您绑定到ViewModel上的命令属性,您在命令中的CanExecute
上返回false,并且按钮被禁用。有时您必须致电CommandManager.InvalidateRequerySuggested()
。
这并不能解释您的代码无效的原因。说实话,它看起来不错。