【发布时间】:2018-01-28 21:27:44
【问题描述】:
好的,我在解决这个问题时遇到了问题。我发现的大多数教程要么不完整,要么解释得不够好。
我使用 Caliburn.Micro 创建了一个测试 WPF 应用程序,该应用程序的主窗口 (ShellViewModel) 有一个文本框和一个按钮,该按钮会打开一个带有文本框和另一个按钮的第二个窗口。当用户在第二个窗口中添加文本并单击“发送”时,POCO 对象被创建并应该被发送到第一个窗口并显示在 ShellViewModel 的文本框中。
我不确定我哪里出错了,似乎没有很多文章可以帮助解决这个问题。
我尝试使用以下文章寻求帮助: https://claytonone.wordpress.com/2014/06/14/caliburn-micro-part-1-getting-started/
https://caliburnmicro.com/documentation/event-aggregator
******EDIT - 按照中的说明重新编程上述项目 https://caliburnmicro.com/documentation/event-aggregator 下面是这个项目的代码。请注意,我添加了一个 POCO 类来存储我想要发送的数据并将其发送到另一个窗口,这更多的是我正在处理的主要项目中的最终目标。
我现在遇到的问题: 1. 当我运行教程设计的程序时,VS 报错说没有无参数的构造函数。为此,我尝试添加构造函数。现在程序运行了。 2. 当我在第二个窗口中输入文本并单击发送时,我得到一个“空引用错误”,但如果我调试“ToSend”对象,则会创建并填充正确的数据。
AppBootStrapper:
namespace CaliburnMicro
{
class AppBootstrapper : BootstrapperBase
{
private readonly SimpleContainer _container = new SimpleContainer();
public AppBootstrapper()
{
Initialize();
}
protected override void OnStartup(object sender, StartupEventArgs e)
{
DisplayRootViewFor<ShellViewModel>();
}
protected override void Configure()
{
_container.Singleton<IEventAggregator, EventAggregator>();
}
}
}
ShellViewModel:
namespace CaliburnMicro.ViewModels
{
class ShellViewModel : Screen, IHandle<EventMessage>
{
private string _messageBox;
private readonly IEventAggregator _eventAggregator;
public string MessageBox
{
get { return _messageBox; }
set
{
_messageBox = value;
NotifyOfPropertyChange(() => MessageBox);
}
}
public ShellViewModel(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
_eventAggregator.Subscribe(this);
}
public ShellViewModel()
{
}
public void OpenWindow()
{
WindowManager wm = new WindowManager();
SecondWindowViewModel swm = new SecondWindowViewModel(_eventAggregator);
wm.ShowWindow(swm);
}
public void Handle(EventMessage message)
{
MessageBox = message.Text;
}
}
}
第二个窗口视图模型
namespace CaliburnMicro.ViewModels
{
class SecondWindowViewModel: Screen
{
private string _secondTextBox;
private readonly IEventAggregator _eventAggregator;
public EventMessage Tosend = new EventMessage();
public string SecondTextBox
{
get { return _secondTextBox; }
set
{
_secondTextBox = value;
NotifyOfPropertyChange(() => SecondTextBox);
}
}
public SecondWindowViewModel(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
}
public void SendBack()
{
Tosend.Text = SecondTextBox;
_eventAggregator.PublishOnUIThread(Tosend);
Thread.Sleep(1000); //I wanted the app to wait a second before closing
TryClose();
}
}
}
这是我想从第二个发回主窗口的 POCO。
namespace CaliburnMicro.Models
{
class EventMessage
{
public string Text { get; set; }
}
}
【问题讨论】:
-
字符串是否到达了
Handle内的ShellViewModel?
标签: c# wpf caliburn.micro eventaggregator