<DatePicker Grid.Column="0" Margin="8" Padding="5" x:Name="from"/>
<DatePicker Grid.Column="1" Margin="8" Padding="5" x:Name="to"/>
和一个按钮
<Button Grid.Row="2" cal:Message.Attach="[Action RunOtherView($dataContext)]" Content="Go" Margin="8" HorizontalAlignment="Center"/>
我希望当我选择两个日期时,按下按钮后,两个日期将在SecondViewModel中传递,例如在List Parameters中的情况。 但是在SecondViewModel的构造函数中,“Parameters”始终为null。 错误在哪里?如何将这些参数从一个屏幕传递到另一个屏幕? 感谢
public class ShellViewModel : Conductor<IScreen>.Collection.OneActive, IShell
{
protected override void OnActivate()
{
base.OnActivate();
ActivateItem(IoC.Get<IMainViewModel>());
}
public void RunOtherView()
{
var crvm = IoC.Get<ISecondViewModel>();
crvm.Parameters = new List<DateTime>();
crvm.Parameters.Add((DateTime)d.from);
crvm.Parameters.Add((DateTime)d.to);
ActivateItem(crvm);
}
}
public class MainViewModel : Screen, IMainViewModel
{
public DateTime? from { get; set; }
public DateTime? to { get; set; }
}
public class SecondViewModel : Screen, ISecondViewModel
{
public List<DateTime> Parameters { get; set; }
protected override void OnActivate()
{
base.OnActivate();
}
public SecondViewModel()
{
//Parameters is always null
PersonalList = CollectionViewSource.GetDefaultView(Db.UpdateInformation(Parameters));
}
public override void TryClose(bool? dialogResult)
{
TryClose(dialogResult);
}
}
答案 0 :(得分:3)
ViewModels可以通过EventAggregator进行通信。您需要创建事件并在侦听视图模型中告知他们期望的事件。我通常会制作一个“事件”文件夹来放置它。
示例:
活动:
public class FooEvent
{
public FooEvent(bool foo)
{
Foo = foo;
}
public bool Foo { get; private set; }
}
第一个屏幕
public class FirstViewModel : Screen
{
private readonly IEventAggregator _events;
[ImportingConstructor]
public FirstViewModel(IEventAggregator events)
{
DisplayName = "First screen";
_events = events;
}
public void PublishFooEvent()
{
_events.Publish(new FooEvent(true));
}
第二个屏幕
public class SecondViewModel : Screen, IHandle<FooEvent>
{
private readonly IEventAggregator events;
[ImportingConstructor]
public SecondViewModel(IEventAggregator events)
{
DisplayName = "Second screen";
this.events = events;
events.Subscribe(this);
}
public bool Bar{get;set;}
public void Handle(FooEvent message)
{
Bar = message.Foo;
}
}
希望它有所帮助。