最好用 PRISM(Prism.Core 6.2,Prism.Windows 6.02)编写,但我也想知道如何在没有 Prism 的情况下使用普通 MVVM 将命令绑定到 UWP 中的页面加载/加载事件。
在 WPF 中,可以通过以下方式实现:
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>
Run Code Online (Sandbox Code Playgroud)
在视图模型中
public ICommand LoadedCommand { get; private set; }
public TheViewModelConstructor()
{
LoadedCommand = new DelegateCommand(Load);
}
private async void Load()
{
// Do stuff
}
Run Code Online (Sandbox Code Playgroud)
但是在 UWP 中,System.Windows.Interactivity 并不存在。简单地绑定
Loaded="{Binding LoadedCommand}"
Run Code Online (Sandbox Code Playgroud)
或者
Loading="{Binding LoadingCommand}"
Run Code Online (Sandbox Code Playgroud)
将得到编译错误“对象引用未设置对象的实例”。
我想这样做的原因是因为有一个异步方法需要在页面加载期间或之后完成(它不能在 ViewModel 构造函数中)。我可以轻松地用代码隐藏它,但这不是 MVVM。
如何正确绑定此命令?
我很抱歉这个问题很基本。我刚刚学习了WPF,但我无法通过简单的两种方式将textbox.text绑定为字符串属性。
XAML代码:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid x:Name="StuInfo">
<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="10,26,0,0" TextWrapping="Wrap" Text="{Binding Path=str,Mode=TwoWay}" VerticalAlignment="Top" Width="120"/>
<Button x:Name="button" Content="Check" HorizontalAlignment="Left" Margin="10,67,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>
</Grid>
Run Code Online (Sandbox Code Playgroud)
C#代码
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
str = "OK";
}
public string str { get; set; }
private void button_Click(object sender, RoutedEventArgs e)
{
Console.WriteLine(str);
}
}
Run Code Online (Sandbox Code Playgroud)
首先,文本框未显示“确定”,但为空白。然后,我在文本框中键入了不同的文本,例如:“ blablabla”,不带引号。然后,我单击按钮以检查我的str属性是否已更新。显然,str仍包含“确定”。
我在这里做错了什么?我想念什么使绑定工作?
使用.Net Framework,可以在这里实现:如何获取当前的ProcessID?.
但是如何在UWP中获得当前的PorcessId?System.Diagnostics甚至没有Process类.