使用 MVVM 绑定 UWP 页面加载/加载到命令 [英] Binding UWP Page Loading/ Loaded to command with MVVM
问题描述
最好用 PRISM(Prism.Core 6.2、Prism.Windows 6.02)编写,但我也想知道如何在没有 Prism 的情况下使用普通 MVVM 将命令绑定到 UWP 中的页面加载/加载事件.
Preferrably written in PRISM (Prism.Core 6.2, Prism.Windows 6.02), but I also would like to know how to bind Command to Page Loading/ Loaded event in UWP with normal MVVM without Prism.
在 WPF 中,可以通过以下方式实现:
In WPF, it is achievable with:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding LoadedCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
在视图模型中
public ICommand LoadedCommand { get; private set; }
public TheViewModelConstructor()
{
LoadedCommand = new DelegateCommand(Load);
}
private async void Load()
{
// Do stuff
}
但在 UWP 中,System.Windows.Interactivity 并不存在.简单地用
But in UWP, System.Windows.Interactivity does not exist. Simply binding with
Loaded="{Binding LoadedCommand}"
或
Loading="{Binding LoadingCommand}"
将得到编译错误对象引用未设置对象的实例".
will get compile error "Object reference not set an instance of an object".
我想这样做的原因是有一个异步方法需要在页面加载期间或之后完成(它不能在 ViewModel 构造函数中).我可以很容易地用代码隐藏,但这不是 MVVM.
The reason I wanted to do this is because there is an async method that needs to be done during or after Page is loaded (it cannot be inside ViewModel constructor). I could do it with code behind easily, but this is not MVVM.
如何正确绑定这个命令?
How can I bind this Command properly?
推荐答案
行为在 UWP 中也可用.只需添加 Microsoft.Xaml.Behaviors.Uwp.Managed打包,您就可以出发了.
Behaviors are also available in UWP. Simply add the Microsoft.Xaml.Behaviors.Uwp.Managed package and you're ready to go.
Microsoft.Xaml.Behaviors.Uwp.Managed v1.x
<interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="Loaded">
<core:InvokeCommandAction Command="{Binding ViewLoadedCommand}" />
</core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>
Microsoft.Xaml.Behaviors.Uwp.Managed v2.x
<interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="Loaded">
<core:EventTriggerBehavior.Actions>
<core:InvokeCommandAction Command="{Binding ViewLoadedCommand}" />
</core:EventTriggerBehavior.Actions>
</core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>
这篇关于使用 MVVM 绑定 UWP 页面加载/加载到命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!