我在视图中遇到错误处理问题。我使用 caliburn.micro 和 MEF。
我的虚拟机如下所示:
[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
}
如果我有一些错误,我将属性 AllPropertiesValid 设置为 false。我将此属性绑定在 Button 属性 IsEnabled 上。
所以在视图中我有这个:
<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 按钮仍处于启用状态。我检查 AllPropertiesValid 的值(我在标签上绑定此属性并且标签内容为假)是否为假。
怎么了 ?感谢提前。
编辑:在设计器中按钮被禁用,但加载时窗口按钮被启用。