命令 主要用于在 ViewModel 和用户界面之间实现清晰的分离。事件订阅和 命令 有什么区别呢?考虑以下示例:
public App ()
{
Button button = new Button
{
Text = "Press me",
};
button.Clicked += Button_Clicked;
// The root page of your application
MainPage = new ContentPage {
Content = new StackLayout {
VerticalOptions = LayoutOptions.Center,
Children = {
button,
}
}
};
}
private void Button_Clicked(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("Pressed!");
}
对比。
public App ()
{
Button button = new Button
{
Text = "Press me",
};
button.Command = new Command(() => System.Diagnostics.Debug.WriteLine("Pressed!"));
// The root page of your application
MainPage = new ContentPage {
Content = new StackLayout {
VerticalOptions = LayoutOptions.Center,
Children = {
button,
}
}
};
}
关于内存管理,应该在事件中取消订阅。对于命令,这也是有效的吗?应该在哪里订阅/取消订阅事件?是在 OnAppearing()
和 OnDisappearing()
中吗?