我仍在学习C#MVVM WPF,在理解一些概念时遇到了一些困难,我已经尝试了一些类似的东西,但遗憾的是没有结果。
所以我想>>如果登录成功打开了一个新的ViewModel,并将一个类(你可以在评论中看到,确切的位置)传递给GeneralViewModel,有人能帮我这里一些代码吗,这样你就能更好地理解。
提前感谢:)
LoginViewModel
WifiAP wa;
#region fields
private TokenRequest tk;
public DelegateCommand _loginCommand { get; set; }
public LoginViewModel()
{
wa = new WifiAP();
_loginCommand = new DelegateCommand(
(s) => { login(); }, //Execute
(s) => { return !string.IsNullOrEmpty(_email); } //CanExecute
);
}
public DelegateCommand LoginCommand
{
get { return _loginCommand; }
}
public async void login()
{
var sendRequest = new TokenRequest
{
email = Email,
mac = getMac(),
platform="windowsdesktop"
};
//Get Token
var response = await CommunicationWebServices.PostASM("self/token", "",sendRequest);
if(response.StatusCode == HttpStatusCode.OK)
{
string responseS = await response.Content.ReadAsStringAsync();
var aux = JsonConvert.DeserializeObject<TokenOK>(responseS); // I have the Token in the Aux
var passwordMD5 = hashingMD5(Password);
var stringConcat = aux.token + passwordMD5;
var finalMD5 = hashingMD5(stringConcat);
// Now you can login
var sendRequestLogin = new LoginRequest
{
email = Email,
tokenpassword = finalMD5,
mac = getMac(),
platform = "windowsdesktop"
};
var responseLogin = await CommunicationWebServices.PostASM("self/login", aux.token, sendRequestLogin);
if(responseLogin.StatusCode == HttpStatusCode.OK)
{
string responseL = await responseLogin.Content.ReadAsStringAsync();
var auth = JsonConvert.DeserializeObject<LoginAnswer>(responseL);
// Change to GeneralViewModel and send the auth variable
}else {//...}}
登录视图
<UserControl.DataContext>
<ViewModel:LoginViewModel/>
</UserControl.DataContext>
<Button x:Name="buttonLogin" Content="Login"
Command="{Binding LoginCommand}" HorizontalAlignment="Left" Margin="274,305,0,0" VerticalAlignment="Top" Width="248" Style="{DynamicResource FlatButtonStyle}" Height="30" />
从前面的答案开始,你只需要稍微改变一下,就可以调用
windowFactory.CreateNewWindow(newViewModel);
这可以很容易地实现为
public class ProductionWindowFactory: IWindowFactory
{
#region Implementation of INewWindowFactory
public void CreateNewWindow(AViewModel newWindowViewModel)
{
NewWindow window = new NewWindow()
{
DataContext = newWindowViewModel;
};
window.Show();
}
#endregion
}
所以最后你的代码可能和一样
GeneralViewModel generalViewModel = new GeneralViewModel(auth);
windowFactory.CreateGeneralWindow(generalViewModel);