Mvvm奇怪的使者行为 [英] Mvvm strange messenger behaviour
问题描述
我正在尝试在两个ViewModel之间传递用户。为此,我使用的是MVVM light Messenger框架。即使遇到断点,我尝试操作传递给第二个ViewModel的模型,但是一些绑定到属性的TextBlocks也不会更新。
我尝试过:
以下是当有人点击登录按钮时我通过用户的方式:
I am trying to pass a User between two ViewModels. To do this I am using the MVVM light Messenger framework. Even though a breakpoint is hit where I try to action the model that is passed to the second ViewModel, some TextBlocks that are bound to properties are not updated.
What I have tried:
Here is how I pass the 'User' when someone clicks a login button:
#region Login
private DelegateCommand _loginCommand;
public ICommand LoginCommand
{
get
{
_loginCommand = new DelegateCommand(param => Login());
return _loginCommand;
}
}
private async void Login()
{
var waitWindow = new PleaseWaitWindow();
waitWindow.Show();
if (await LoginCheck())
{
// TODO: Navigate to the DashboardView
Messenger.Default.Send(new ChangePage(typeof(DashboardViewModel)));
Messenger.Default.Send(_chosenUser);
}
waitWindow.Close();
}
#endregion
以下是我订阅该邮件并使用其内容的方式:
Here is how I subscribe to that message and use its contents:
public DashboardViewModel()
{
Messenger.Default.Register<User>(this, OnUserReceived);
Messenger.Default.Register<ChangePage>(this, ChangePage); // Register to Messenger to change Views hosted in ContentControl
}
private void OnUserReceived(User user)
{
FirstName = user.FirstName; // Breakpoint is hit here with correct value
LastName = user.LastName;
}
和绑定到FirstName和LastName属性的两个TextBlock ..:
And the two TextBlocks that are bound to the FirstName and LastName properties..:
<StackPanel VerticalAlignment="Center" Margin="5">
<TextBlock Text="{Binding FirstName}" Foreground="White" Margin="5" FontSize="18"/>
<TextBlock Text="{Binding LastName}" Foreground="White" FontWeight="Bold" Margin="5" FontSize="20"/>
</StackPanel>
如果我设置一个断点来操作Messenger,那么FirstName和LastName设置为正确的价值观但是,TextBlocks没有更新,它们的文本仍然是空的。
我在DashboardView上实现了一个测试按钮,只需设置FirstName =Test;这确实更新TextBlock说文本所以我很困惑为什么传入一种类型的用户并使用其FirstName和LastName不起作用。
编辑:
If I set a breakpoint where I action the Messenger then FirstName and LastName are set to the correct values. However, the TextBlocks are not updated and their text remains null.
I have implemented a test button on the DashboardView that simply sets FirstName ="Test"; and this does update the TextBlock to say Text so I am confused as to why passing in a type of User and using its FirstName and LastName doesn't work.
private void OnUserReceived(User user)
{
Application.Current.Dispatcher.Invoke(() =>
{
FirstName = user.FirstName;
LastName = user.LastName;
});
}
推荐答案
这种行为很正常,
因为信使不同线程。
我也有过这种现象。
您应该使用调度员:
This behaviour is quite normal,
as the messenger is on a different thread.
I also had this phenomenon once.
You should use a dispatcher:
Application.Current.Dispatcher.Invoke(() =>
{
FirstName = user.FirstName; // Breakpoint is hit here with correct value
LastName = user.LastName;
});
这篇关于Mvvm奇怪的使者行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!