【问题标题】:(Xamarin) pass data from XAML to XAML.cs(Xamarin) 将数据从 XAML 传递到 XAML.cs
【发布时间】:2019-07-29 14:14:29
【问题描述】:

我来自 asp.net 背景,所以我在理解整个 MVVM 想法时遇到了一些麻烦。

我有一个列表视图,里面充满了消息(它是一种论坛应用程序)。每条消息都有一个按钮,当按下该按钮时,应询问用户是否要删除,然后在确认后删除。

我曾尝试使用命令,但随后出现错误(您实际上可以调用 xaml.cs 而不是 ViewModel 的命令吗?)我还尝试使用事件和命令参数,但这也给了我错误。

有事件: XAML(内部图像)

              <Image.GestureRecognizers>
                    <TapGestureRecognizer Tapped="MessageClicked" CommandParameter="{Binding MessageId}"/>
              </Image.GestureRecognizers>

代码背后

                async void MessageClicked(object sender, TappedEventArgs e)
                {
                    string action = "";
        #if __IOS__
                    action = await DisplayActionSheet("Message options", "Cancel", "Delete", "Edit");
        #else
                    action = await DisplayActionSheet("Message options", "Cancel", null, "Edit", "Delete");
        #endif
                    switch (action)
                    {
                        case "Delete":
                            if (await DisplayAlert("Delete message?", "Are you sure you want to delete this message?", "Yes", "No"))
                            {
                                DeleteMessage((int)(e.Parameter));
                            }
                            break;
                        case "Edit":
                            EditMessage((int)(e.Parameter));
                            break;
                    }
                }

错误:EventHandler“XamarinTest.MainPage/_anonXamlCDataTemplate_0.MessageClicked”的签名(参数1)与事件类型不匹配

使用命令: XAML(内部图片)

    <Image.GestureRecognizers>
        <TapGestureRecognizer Command="MessageOptions" CommandParameter="{Binding MessageId}"/>
    </Image.GestureRecognizers>

后面的代码:

    public Command<int> MessageOptions
            {
                get { return new Command<int>(i => MessageClickedCommand(i)); }
            }

            async void MessageClickedCommand(int id)
            {
                await DisplayAlert("Information", $"The id of this message is: {id}", "Ok");
            }

错误: 找不到“命令”的属性、可绑定属性或事件,或者值和属性之间的类型不匹配。

在 asp.net 中,我只需将数据属性附加到调用函数的对象,以便函数可以检索数据本身。 HTML 和 Javascript 看起来像:

    <div class="functionDiv" data-id="1">
    </div>

    $(document).ready(function() { 
        $(".functionDiv").bind("click", function() {
        var $data = $(this).data("id");
        console.log($data);
      });
    });

我想先去后端,因为我可以在那里调用显示函数。然后我可以去 ViewModel 做实际的删除

编辑 我找到了一种可行的方法,但是感觉很脏

    async void MessageClicked(object sender, EventArgs e)
    {
        int id = Converters.GetParameter<int>(sender);
    }

    public static Y GetParameter<Y>(object sender)
    {
        var item = (TapGestureRecognizer)(sender as View).GestureRecognizers[0];    
        return (Y)item.CommandParameter;
    }

    <Image.GestureRecognizers>
        <TapGestureRecognizer Tapped="MessageClicked" CommandParameter="{Binding MessageId}"/>
    </Image.GestureRecognizers>

【问题讨论】:

  • 有什么更新吗?请在此处提供反馈。

标签: xamarin


【解决方案1】:

根据你的描述,你想在xamarin.forms中使用mvvm模式将数据传给.cs,你需要先新建类继承Icommand,

 public class RelayCommand1: ICommand
{
    private readonly Predicate<object> _canExecute;
    private readonly Action<object> _execute;

    public RelayCommand1(Action<object> execute)
        : this(execute, null)
    {
    }

    public RelayCommand1(Action<object> execute, Predicate<object> canExecute)
    {
        _execute = execute;
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute(parameter);
    }

    public event EventHandler CanExecuteChanged;


    public void Execute(object parameter)
    {
        _execute(parameter);
    }
}

然后使用绑定按钮命令。

  <Button
                                Command="{Binding BindingContext.command, Source={x:Reference listview1}}"
                                CommandParameter="{Binding Id}"
                                Text="Delete item" />

我为你创建了新的简单示例,你可以看看:

XAML:

 <ListView x:Name="listview1" ItemsSource="{Binding persons}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Horizontal">
                            <Label Text="{Binding Id}" />
                            <Label Text="{Binding name}" />
                            <Button
                                Command="{Binding BindingContext.command, Source={x:Reference listview1}}"
                                CommandParameter="{Binding Id}"
                                Text="Delete item" />
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

XAML.cs

public partial class Page1 : ContentPage
{
    public ObservableCollection<person> persons { get; set; }
    public RelayCommand1 command { get; set; }

    public Page1 ()
    {
        InitializeComponent ();
        persons = new ObservableCollection<person>();

        for(int i =0;i<20;i++)
        {
            person p = new person()
            {
                Id = i,
                name = "cherry" + i

            };
            persons.Add(p);

            command = new RelayCommand1(obj => method1((int)obj));
        }
        this.BindingContext = this;
    }
    public void method1(int Id)
    {
        persons.RemoveAt(Id);

    }
}

public class person
{
    public int Id { get; set; }
    public string name { get; set; }
}

【讨论】:

    猜你喜欢
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 2019-01-03
    相关资源
    最近更新 更多