c# - 如何从 xamarin 表单中的绑定(bind)命令调用函数

标签 c# xaml binding xamarin.forms icommand

我想知道如何从 xamarin 表单中的命令调用函数。我目前正在使用 https://github.com/robinmanuelthiel/swipecards设置一叠刷卡。我能够看到在元文件中有两个可绑定(bind)属性来处理左右滑动。

从元文件中截取:

public static BindableProperty SwipedRightCommandProperty;
public static BindableProperty SwipedLeftCommandProperty;

public Action<object> SwipedRight;
public Action<object> SwipedLeft;

public ICommand SwipedRightCommand { get; set; }
public ICommand SwipedLeftCommand { get; set; }

我可以在我的 XAML 内容页面中绑定(bind) ItemSource,但我似乎无法绑定(bind)到向左滑动和向右滑动命令。

XAML:

<swipecards:CardStackView
            x:Name="CardStackView"
            ItemsSource="{Binding MyList}"
            SwipedLeftCommand="{Binding SwipedLeft}"
            SwipedRightCommand="{Binding SwipedRight}"
            CardMoveDistance="60"
            Grid.Column="0" Grid.ColumnSpan="3"
            Grid.Row="0">

C#(在我的 View 模型中)

public void SwipedLeft(object obj)
{
    System.Diagnostics.Debug.WriteLine("Something Happened");
}

public void SwipedRight(object obj)
{
    System.Diagnostics.Debug.WriteLine("Something Happened");
}

有人知道如何正确绑定(bind)命令以便正确触发我的功能吗?

最佳答案

将命令绑定(bind)到经典的 Xamarin 按钮控件如下所示:

XAML:

<Button Command="{Binding SwipeLeftCommand}" CommandParameter="{Binding SwipeLeftCommandParam}" />

View 模型:

public ICommand SwipedRightCommand { get; } //getter is sufficient


public YourViewModel()
{
    //plain code (often comes with bad maintainability)
    SwipeLeftCommand = new Command(() => { /* code */ });

    //simple method attachment (with command parameter)
    SwipeLeftCommand = new Command((commandParameter) => SwipedLeft(commandParameter));

    //simple method + async/await call
    SwipeLeftCommand = new Command(async (commandParameter) => await SwipedLeft(commandParameter));
}

关于c# - 如何从 xamarin 表单中的绑定(bind)命令调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47853666/

相关文章:

silverlight - 在 WP7 中设置整个背景图像/颜色

c# - 如何构建印度尼西亚电话号码正则表达式

xaml - 将属性绑定(bind)到 Listview DataTemplate 中的元素

c# - 在 Azure Functions v2 中添加中间件等

xaml - 如何在 UWP 中进行相对源模式查找祖先(或等效项)

c# - WPF 延迟绑定(bind)无法正常工作

具有 int 值的 JavaFX 绑定(bind)标签

Cocoa 绑定(bind)和应用程序首选项 - 崩溃

c# - 在所有者类中使用属​​性与支持字段

c# - 在 C# 中分割、编码和加入视频部分