WPF MVVM Caliburn 在特定 ViewModel 中显示所有 ErrorMsgs

WPF MVVM Caliburn Displaying all ErrorMsgs in a specific ViewModel

我正在考虑在 shellview 的特定区域向用户显示错误消息。

所以我在我的 ShellViewModel 中实例化了 ErrorViewModel,ErrorModel 显示正确。带有 ViewModel 的文本块显示了它应有的初始值。

但是如果我通过另一个 ViewModel(例如 LoginViewModel)的 public 方法传递一个字符串,则错误字符串会传递给 ErrorViewModel 并且还会触发 NotifyOfPropertyChange(() => PublishErrorMsg) 但文本块不是改变。

不明白为什么文本块的内容不会改变。

错误视图模型:

public class ErrorViewModel : Screen
{
    private string publishErrorMsg;
    public string PublishErrorMsg 
    { 
        get { return publishErrorMsg; }
        set
        {
            publishErrorMsg = value;
            NotifyOfPropertyChange(() => PublishErrorMsg);
        }
    } 

    public void ShowError(string msg) {
        PublishErrorMsg = msg;
        //  MessageBox.Show(msg);
        NotifyOfPropertyChange(() => PublishErrorMsg);
    }
}

XAML 错误视图:

<UserControl x:Class="Views.ErrorView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:Views"
         mc:Ignorable="d" 
         d:DesignHeight="40" d:DesignWidth="800" Background="White">
<Grid>
    <DockPanel  VerticalAlignment="Bottom" Height="40" Background="#FF474A57">
        <TextBlock Text="{Binding PublishErrorMsg}"
                       Width="200" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="#FFE69393" FontSize="14">
        </TextBlock>
    </DockPanel>
</Grid>

接下来触发事件的部分:

        public void LogIn() {
        this.container.GetInstance<ErrorViewModel>().ShowError("User logged in");
        try {
            ResetPublishMsg();

            ActiveUserModel.CreateIfAuthenticated(UserName, Password);

            events.PublishOnUIThread(new LogOnEvent());
        }
        catch (Exception ex) {
            this.container.GetInstance<ErrorViewModel>().PublishErrorMsg = ex.Message;
        }
    }

感谢您的帮助!

也许您忘记订阅活动了?见 EventAggregator

public class ErrorViewModel : Screen, IHandle<LogOnEvent> 
{
        private readonly IEventAggregator _eventAggregator;

        public ErrorViewModel(IEventAggregator eventAggregator) {
            _eventAggregator = eventAggregator;
            _eventAggregator.Subscribe(this);
        }



       public void Handle(LogOnEvent message) {
            // Handle the message here.
        }

}