Xamarin形式。单击按钮后从ViewModel加载View

use*_*098 1 c# data-binding xamarin.forms

如何才能做到这一点?我已经能够使用xaml来实现它,就像这样。我将如何使用ViewModel模式来做到这一点?

View.xaml

<Button Margin="50,0,20,20" FontSize="Large" Text="Test" Clicked="Button_Clicked">
                </Button>
Run Code Online (Sandbox Code Playgroud)

View.cs

private void Button_Clicked(object sender, EventArgs e)
{
    Get_LessonViewAsync();            
}

private async void Get_LessonViewAsync()
{
    var view = new LessonView();
    await Navigation.PushModalAsync(view);
}
Run Code Online (Sandbox Code Playgroud)

Fra*_*sen 5

在xaml中,您可以使用Command属性进行绑定:

<Button Margin="50,0,20,20" FontSize="Large" Text="Test" Command="{Binding ButtonCommand}"></Button>
Run Code Online (Sandbox Code Playgroud)

在您的ViewModel中:

public ICommand ButtonCommand { get; private set; }
public ICommand GoLeftCommand { get; private set; }     
public ICommand GoRightCommand { get; private set; }     

public DemoViewModel ()
{
    ...
    ButtonCommand = new Command (() => {
            var view = new LessonView();
            await Navigation.PushModalAsync(view);
        });
    GoLeftCommand = new Command (() => {
            var view = new LeftView();
            await Navigation.PushModalAsync(view);
        });
    GoRightCommand = new Command (() => {
            var view = new RightView();
            await Navigation.PushModalAsync(view);
        });
}
Run Code Online (Sandbox Code Playgroud)

摘录自:David Britch的https://blog.xamarin.com/simplifying-events-with-commanding/