gpt4 book ai didi

c# - View 模型的可见性不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 19:20:15 25 4
gpt4 key购买 nike

我有一个带有登录 View 模型的登录 View ,遇到了一个让我抓狂的问题。请注意,我使用的是 MVVM Light。

在 View 模型中,我有三个可见性属性,它们应该根据 View 模型的状态隐藏 View 中的元素。

我的属性如下所示,所有属性都触发 PropertyChangedEvent:

public Visibility ErrorPanelVisibility
public Visibility LoginPanelVisibility
public Visibility LoadingPanelVisibility

绑定(bind)看起来像这样(省略边距等):

<Border Visibility="{Binding ErrorPanelVisibility}">
<StackPanel Visibility="{Binding LoginPanelVisibility}">
<StackPanel Visibility="{Binding LoadingPanelVisibility}">

当用户按下登录按钮时,在 View 模型中执行此方法的命令会更改可见性:

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;
}
});
}

问题是面板没有被折叠或更改为在 View 中可见,更改没有反射(reflect)在 View 中。当我将可见性设置为可见但未折叠时,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;
}

这里有没有明显的错误,或者有人能找出我做错了什么吗?

最佳答案

还有。我建议您避免在 ViewModel 中使用 UI 类型。尝试使用 bool 值并使用 BoolToVisibilityConverter。

附言确保为控件设置 DataContext。

关于c# - View 模型的可见性不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12929937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com