我有一个带有登录视图模型的登录视图,遇到了一个让我发疯的问题。请注意,我使用的是 MVVM Light。
在视图模型中,我有三个可见性属性,它们应该根据视图模型的状态隐藏视图中的元素。
我的属性长这样,都触发了PropertyChangedEvent:
public Visibility ErrorPanelVisibility
public Visibility LoginPanelVisibility
public Visibility LoadingPanelVisibility
绑定看起来像这样(省略边距等):
<Border Visibility="{Binding ErrorPanelVisibility}">
<StackPanel Visibility="{Binding LoginPanelVisibility}">
<StackPanel Visibility="{Binding LoadingPanelVisibility}">
当用户按下登录按钮时,可见性会通过在视图模型中执行此方法的命令来更改:
private void ExecuteLogin()
{
ErrorPanelVisibility = Visibility.Collapsed;
LoginPanelVisibility = Visibility.Collapsed;
LoadingPanelVisibility = Visibility.Visible;
// This method takes a few seconds to complete.
Login(errorMessage =>
{
if (!String.IsNullOrEmpty(errorMessage))
{
ErrorMessage = errorMessage;
ErrorPanelVisibility = Visibility.Visible;
LoginPanelVisibility = Visibility.Visible;
LoadingPanelVisibility = Visibility.Collapsed;
}
else
{
DialogResult = true;
}
});
}
问题是面板没有被折叠或在视图中更改为可见,更改不会反映在视图中。当我将可见性设置为可见但未折叠时,PropertyChangedEvent 被触发并且 ErrorPanel 正在工作。
编辑:登录方法:
private void Login(Action<string> callback)
{
string errorMessage = string.Empty;
if (SelectedServer == null)
{
errorMessage = "Select server."; //TODO: Translate
}
else if (String.IsNullOrEmpty(Username) || String.IsNullOrEmpty(Password))
{
errorMessage = Resources.WrongUsernameOrPassword;
}
else
{
try
{
// Changed name due to customer information
IWCFClient wcfClient = WCFClient.GetInstance();
LoginObj loginObj = wcfClient.Login(Username, Password);
// Removed some cases to simplify, they all set the errorMessage.
switch (loginObj.LoginStatus)
{
case LoginObj.LoginState.AlreadyLogedin:
errorMessage = Resources.UserAlreadyLoggedOn;
break;
default:
errorMessage = Resources.ErrorOccurred;
break;
}
}
catch (Exception e)
{
errorMessage = e.Message;
}
}
callback(errorMessage);
}
但是,如果我将代码更改为此,面板确实可以工作:
bool login = false;
private void ExecuteLogin()
{
if (login)
{
ErrorPanelVisibility = Visibility.Collapsed;
LoginPanelVisibility = Visibility.Collapsed;
LoadingPanelVisibility = Visibility.Visible;
}
else
{
ErrorPanelVisibility = Visibility.Visible;
LoginPanelVisibility = Visibility.Visible;
LoadingPanelVisibility = Visibility.Collapsed;
}
login = !login;
}
这里有没有明显的错误,或者任何人都可以找出我做错了什么?