【问题标题】:It is possible to save an Object on a Button on Xamarin.Forms? [closed]可以在 Xamarin.Forms 上的按钮上保存对象吗? [关闭]
【发布时间】:2021-04-08 09:30:56
【问题描述】:

如果可以将对象保存到 Xamarin.Forms、C# 上的按钮中,我很想知道。这是我的代码:

public partial class MenuPage : ContentPage{
    public MenuPage(List<Product> products) {
        InitializeComponent();

        grid.RowDefinitions.Add(new RowDefinition());
        grid.RowDefinitions.Add(new RowDefinition());
        grid.RowDefinitions.Add(new RowDefinition());
        grid.ColumnDefinitions.Add(new ColumnDefinition());
        grid.ColumnDefinitions.Add(new ColumnDefinition());

        int product_cont = 0;

        for (int rowIndex = 0; rowIndex < 3; rowIndex++) {
            for (int columnIndex = 0; columnIndex < 2; columnIndex++) {
               Button b = new Button();
               b.Text = products[products_cont].name;
               b.OnButtonClicked += async (sender, e) => {
                   //go to products childs
                   await Navigation.PushAsync(new MenuPage(products[products_cont].childs));
               };
               i++; //next product
               grid.Children.Add(b, columnIndex, rowIndex);
            }
        }
    }
}

按钮显示正确,但是当我按下它们时,products[products_cont].childs 不存在。我想如果我能做这样的事情就可以了:

...
Button b = new Button();
b.Text = products[products_cont].name;
b.SAVE_OBJECT(products[products_cont])
b.OnButtonClicked += async (sender, e) => {
   //go to products childs
   await Navigation.PushAsync(new MenuPage(b.GET_OBJECT.childs));
};
...

【问题讨论】:

    标签: c# android xamarin button


    【解决方案1】:

    你可以使用BindingContext

    Button b = new Button();
    b.Text = products[products_cont].name;
    b.BindingContext = products[products_cont];
    b.OnButtonClicked += NavigateToProduct;
    

    protected void NavigateToProduct(object sender, EventArgs a)
    {                   
        var btn = (Button)sender);
        var product = (Product)sender.BindingContext;
        await Navigation.PushAsync(new MenuPage(product.childs));
    }
    

    【讨论】:

      猜你喜欢
      • 2018-07-06
      • 1970-01-01
      • 1970-01-01
      • 2017-06-24
      • 2011-10-12
      • 1970-01-01
      • 2022-11-03
      • 1970-01-01
      • 2017-10-14
      相关资源
      最近更新 更多