如何将弹出页面按钮绑定到xamarin形式的viewmodel命令属性

时间:2019-03-18 09:09:54

标签: mvvm xamarin.forms

我是MVVM和xamarin形式的新手。我想在mvvm中实现自定义弹出窗口,以下是我的代码 我的Viewmodel是:

public class PopupVM
{
 public ICommand CancelCommand => new Command(async () =>{await 
 Application.Current.MainPage.Navigation.PopModalAsync();});
}

我的弹出页面Xaml:`

<pages:PopupPage.Animation>
    <animations:ScaleAnimation DurationIn="400"
    DurationOut="300"
    EasingIn="SinOut"
    EasingOut="SinIn"
    HasBackgroundAnimation="True"
    PositionIn="Center"
    PositionOut="Center"
    ScaleIn="1.2"
    ScaleOut="0.8" />
</pages:PopupPage.Animation>

<Grid Margin="12"
Padding="24"
BackgroundColor="White"
HorizontalOptions="Center"
VerticalOptions="Center">
    <Grid.RowDefinitions>
    <RowDefinition Height="*"/>
    <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
    <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <StackLayout Orientation="Vertical">
        <Picker Grid.Row="0" Grid.Column="0">
            <Picker.Items>
            <x:String>....</x:String>
            </Picker.Items>
        </Picker>

    <StackLayout Orientation="Vertical" Grid.Column="0" Grid.Row="1">
        <StackLayout Orientation="Horizontal" >
            <Label Text="A"/>**strong text**
            <Picker>
            <Picker.Items>
            <x:String>Item1</x:String>
            <x:String>Item2</x:String>
            <x:String>Item3</x:String>
            </Picker.Items>
            </Picker>
        </StackLayout>

        <StackLayout Orientation="Horizontal" >
            <Label Text="B"/>
            <Picker>
            <Picker.Items>
            <x:String>....</x:String>
            </Picker.Items>
            </Picker>
        </StackLayout>

        <StackLayout Orientation="Horizontal" >
            <Label Text="C"/>
            <Picker>
            <Picker.Items>
            <x:String>....</x:String>
            </Picker.Items>
            </Picker>
        </StackLayout>
    </StackLayout>
        <Button Text="Ok"/>
        <Button Text="Cancel" x:Name="cnclBtn" />
    </StackLayout>
</Grid>

我的Popupxaml.cs页面为:

public partial class MyPopupPage 
{
static PopupVM vm;
public MyPopupPage ()
{
    InitializeComponent ();

    if (vm==null)
    { vm = new PopupVM(); }
    BindingContext = vm;
}
}

我不会误会我的意思。而且我还需要自定义弹出窗口而不是默认的显示警报

1 个答案:

答案 0 :(得分:-1)

<Button Text="Cancel" x:Name="cnclBtn" Command="{binding CancelCommand}" />

有关命令和绑定的更多信息,请访问this