简体   繁体   English

Xamarin.forms:如何从 Listview 获取对象值

[英]Xamarin.forms: How to get Object value from a Listview

I am placing a stepper inside a Listview.我在 Listview 中放置了一个步进器。 I would like to know which Item the Stepper belong to when I change it.当我改变它时,我想知道步进器属于哪个项目。 Here is the Listview.这是列表视图。 I would like to know, when I modify the stepper's value, which EAN is part of the same ViewCell.我想知道,当我修改步进器的值时,哪个 EAN 是同一个 ViewCell 的一部分。

        <ListView x:Name="ItemsListView"
            ItemsSource="{Binding Items}"
            VerticalOptions="FillAndExpand"
            HasUnevenRows="true"
            RefreshCommand="{Binding LoadItemsCommand}"
            IsPullToRefreshEnabled="true"
            IsRefreshing="{Binding IsBusy, Mode=OneWay}"
            CachingStrategy="RecycleElement"
            ItemTapped="OnItemSelected"
              >
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Padding="10" Orientation="Vertical" HorizontalOptions="FillAndExpand">
                            <Label Text="{Binding Name}" LineBreakMode="WordWrap"  FontSize="16" HorizontalOptions="FillAndExpand"  />
                            <Label Text="{Binding QuantityExpectedDisplay}" LineBreakMode="WordWrap"  FontSize="10" HorizontalOptions="FillAndExpand"  />
                            <Label Text="{Binding EAN}" LineBreakMode="WordWrap"  FontSize="10" HorizontalOptions="FillAndExpand"  />
                            <Stepper Value="{Binding QuantityDefect}" Minimum="0" Maximum="{Binding Quantity}" HorizontalOptions="FillAndExpand" ValueChanged="Stepper_ValueChanged" />
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

So that I can use that ean later to find the corresponding line.这样我以后可以使用该 ean 来查找相应的行。 (In the example, I would like to find the ListItem, or at least its EAN in test, rather than putting a new one) (在示例中,我想在测试中找到 ListItem,或者至少是它的 EAN,而不是放一个新的)

    private void Stepper_ValueChanged(object sender, ValueChangedEventArgs e)
    {
        ListItem test = new ListItem();//Here I'd like the ViewCell Values
        var line = viewModel.lines.Find(l => l.Ean == test.EAN);
        line.QuantityOpen = (int)e.NewValue;
    }

Thank you and have a nice day谢谢你,祝你有美好的一天

We generally don't recommend using this method,you can implement INotifyPropertyChanged for your the item of Items .我们一般不推荐使用这种方法,你可以为你的Items实现INotifyPropertyChanged

Suppose the item model is Item.cs , you can implement INotifyPropertyChanged as follows:假设项目模型为Item.cs ,您可以按如下方式实现INotifyPropertyChanged

public class Item: INotifyPropertyChanged
{
    public string Name { get; set; }
    public string QuantityExpectedDisplay{ get; set; }
    public string EAN{ get; set; }

    //public int  QuantityDefect { get; set; }

    int _quantityDefect;
    public int QuantityDefect
    {
        set { SetProperty(ref _quantityDefect, value); }

        get { return _quantityDefect; }
    }

    public int Quantity { get; set; }

    bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
    {
        if (Object.Equals(storage, value))
            return false;

        storage = value;
        OnPropertyChanged(propertyName);
        return true;
    }

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

And in YourPage.xaml ,we can do like this:YourPage.xaml中,我们可以这样做:

    <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <StackLayout Padding="10" Orientation="Vertical" HorizontalOptions="FillAndExpand">
                        <Label Text="{Binding Name}" LineBreakMode="WordWrap"  FontSize="16" HorizontalOptions="FillAndExpand"  />
                        <Label Text="{Binding QuantityExpectedDisplay}" LineBreakMode="WordWrap"  FontSize="10" HorizontalOptions="FillAndExpand"  />
                        <Label Text="{Binding EAN}" LineBreakMode="WordWrap"  FontSize="10" HorizontalOptions="FillAndExpand"  />
                        <Stepper Value="{Binding QuantityDefect}" Minimum="0" Maximum="10" Increment="1" HorizontalOptions="FillAndExpand"  />
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>

Note:笔记:

Once we change the stepper's value, the value of QuantityDefect will change accordingly.一旦我们改变步进器的值, QuantityDefect的值就会相应改变。

Update更新

How can I find more information about this type of binding?如何找到有关此类绑定的更多信息? How is it called, so I can find out how it works for later?它是怎么称呼的,所以我以后可以了解它是如何工作的?

Yes, if we implement INotifyPropertyChanged for Item and change the value, it also change the value of the ItemsSource of current listview.是的,如果我们为 Item 实现INotifyPropertyChanged并更改值,它也会更改当前列表视图的ItemsSource的值。

For example,, suppose the view model of current page is MyViewModel.cs :例如,假设当前页面的视图模型是MyViewModel.cs

    public class MyViewModel
{
    public ObservableCollection<Item> items { get; set; }
    public MyViewModel() {
        items = new ObservableCollection<Item>();

        items.Add(new Item { Name = "Tomato", Quantity = 100, QuantityDefect = 10 });
        items.Add(new Item { Name = "Romaine Lettuce",  Quantity = 100, QuantityDefect = 10 });
        items.Add(new Item { Name = "Zucchini", Quantity = 100, QuantityDefect = 10 });

    }
}

Then we can also get the modified ItemsSource as follows(I added a Button to print the data):然后我们也可以得到修改后的ItemsSource如下(我加了一个Button来打印数据):

public partial class MainViewXaml : ContentPage
{

    MyViewModel viewModel;
    public MainViewXaml ()
    {
        InitializeComponent();

        viewModel = new MyViewModel();
        BindingContext = viewModel;
    }

    private void Stepper_ValueChanged(object sender, ValueChangedEventArgs e)
    {

    }
    // we can get the items here
    private void Button_Clicked(object sender, System.EventArgs e)
    {
        foreach (Item item in viewModel.items) {
            System.Diagnostics.Debug.WriteLine(" name : " + item.Name + "<-----> QuantityDefect = " + item.QuantityDefect);
        }
    }
}

First, see Jessie's answer for the basics of Data Binding to a list of items.首先,请参阅 Jessie 的回答,了解将数据绑定到项目列表的基础知识。

Or see example described in ListView Data Sources .或者参见ListView Data Sources中描述的示例。


In addition, we need a way to tell viewmodel what item has changed.此外,我们需要一种方法来告诉 viewmodel 哪些项目发生了变化。

MessagingCenter can do this.消息中心可以做到这一点。

MyViewModel.cs: MyViewModel.cs:

public MyViewModel()
{
    MessagingCenter.Subscribe<MyItem>(this, "changed", Item_Changed);
}

public ObservableCollection<MyItem> Items { get; set; }

private void Item_Changed(MyItem item)
{
    var index = Items.IndexOf(item);
    // Make sure it is mine.
    if (index >= 0)
    {
        // ...
    }
}

MyItem.cs: MyItem.cs:

int _quantityDefect;
public int QuantityDefect
{
    get => _quantityDefect;
    set
    {
        SetProperty(ref _quantityDefect, value);
        Xamarin.Forms.MessagingCenter.Send<MyItem>(this, "changed");
    }
}

如何从列表中获取密钥<object>在 Firebase 在 Xamarin.Forms 中?<div id="text_translate"><p> I am programming in Xamarin.Forms, I am also using the FirebaseDatabase [dot] net Nuget I have the following method, in connection to my Firebase Realtime Database, which sends a List.</p><pre> public static async Task&lt;bool&gt; PostDetallePedido(List&lt;AgregarCarrito&gt; carrito) { try { var result = await firebase.Child("DetallePedidos").Child(Preferences.Get("idOrder", string.Empty)).PostAsync(carrito); result2 = result.Key; var keyTable = new KeyClass() { keyU = result2, orderId = Preferences.Get("idOrder", string.Empty) }; await firebase.Child("keyTable").Child(Preferences.Get("idOrder", string.Empty)).PostAsync(keyTable); return true; } catch (Exception e) { Debug.WriteLine($"Error:{e}"); return false; } }</pre><p> 我的数据库填充如下<a href="https://i.stack.imgur.com/pBxxr.png" rel="nofollow noreferrer">图1</a></p><p> 使用前面的代码,我可以获得唯一 ID,但我仍然不知道如何获取以自动增量方式生成的值</p><pre>-M7B6xMB19uodzf-C71H | -0 | -1</pre><p> <strong>编辑:</strong></p><pre> public static async Task&lt;List&lt;AgregarCarrito&gt;&gt; GetDetailByUser(int id) { try { var key = await GetKey(id); var value = (await firebase.Child("DetallePedidos").Child(Convert.ToString(id)).Child(key.keyU).OnceAsync&lt;AgregarCarrito&gt;()).Select(item =&gt; new AgregarCarrito { orderId = item.Object.orderId, ProductName = item.Object.ProductName, CustomerId = item.Object.CustomerId, Price = item.Object.Price, TotalAmount = item.Object.TotalAmount, ProductId = item.Object.ProductId, Qty = item.Object.Qty, imageUrl = item.Object.imageUrl, Valor = item.Object.Valor }).ToList(); return value; } catch (Exception e) { Debug.WriteLine($"Error:{e}"); return null; } }</pre><p> 我创建了一个使用 orderId 返回键值的方法,但我仍然无法访问列表的值,在这种情况下,这将是发送列表时以自动增量方式生成的对象</p><p><a href="https://i.stack.imgur.com/ENEas.png" rel="nofollow noreferrer">图 2</a></p></div></object> - How can I get a key from a List <object> in Firebase in Xamarin.Forms?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 xamarin.forms 中获取 ListView 的子项? - How to get children of the ListView in xamarin.forms? Xamarin.Forms在ListView中的条目更改时获取ListView的对象 - Xamarin.Forms Get the object of a ListView when an Entry in the ListView is changed 如何从对象中获取 Xamarin.Forms 元素的名称? - How to get the name of Xamarin.Forms element from object? 从Xamarin.Forms中的对象获取BaseType - Get BaseType from object in Xamarin.Forms 通过委托 (xamarin.forms) 在列表视图中将值从复选框传递到 label - Pass value from checbox to label in listview by delegate (xamarin.forms) Xamarin.Forms JSON对象进入Listview - Xamarin.Forms JSON object into Listview 如何通过打开上下文操作菜单从ListView中获取所选项目? (Xamarin.Forms) - How do I get the selected item from a ListView by opening the context actions menu? (Xamarin.Forms) 如何通过索引从 xamarin 形式的 ListView 对象获取访问视单元? - How to get access viewcell by index from ListView object in xamarin forms? 如何在 Xamarin.Forms ListView 中创建手风琴 - How to create an accordion in Xamarin.Forms ListView 如何从列表中获取密钥<object>在 Firebase 在 Xamarin.Forms 中?<div id="text_translate"><p> I am programming in Xamarin.Forms, I am also using the FirebaseDatabase [dot] net Nuget I have the following method, in connection to my Firebase Realtime Database, which sends a List.</p><pre> public static async Task&lt;bool&gt; PostDetallePedido(List&lt;AgregarCarrito&gt; carrito) { try { var result = await firebase.Child("DetallePedidos").Child(Preferences.Get("idOrder", string.Empty)).PostAsync(carrito); result2 = result.Key; var keyTable = new KeyClass() { keyU = result2, orderId = Preferences.Get("idOrder", string.Empty) }; await firebase.Child("keyTable").Child(Preferences.Get("idOrder", string.Empty)).PostAsync(keyTable); return true; } catch (Exception e) { Debug.WriteLine($"Error:{e}"); return false; } }</pre><p> 我的数据库填充如下<a href="https://i.stack.imgur.com/pBxxr.png" rel="nofollow noreferrer">图1</a></p><p> 使用前面的代码,我可以获得唯一 ID,但我仍然不知道如何获取以自动增量方式生成的值</p><pre>-M7B6xMB19uodzf-C71H | -0 | -1</pre><p> <strong>编辑:</strong></p><pre> public static async Task&lt;List&lt;AgregarCarrito&gt;&gt; GetDetailByUser(int id) { try { var key = await GetKey(id); var value = (await firebase.Child("DetallePedidos").Child(Convert.ToString(id)).Child(key.keyU).OnceAsync&lt;AgregarCarrito&gt;()).Select(item =&gt; new AgregarCarrito { orderId = item.Object.orderId, ProductName = item.Object.ProductName, CustomerId = item.Object.CustomerId, Price = item.Object.Price, TotalAmount = item.Object.TotalAmount, ProductId = item.Object.ProductId, Qty = item.Object.Qty, imageUrl = item.Object.imageUrl, Valor = item.Object.Valor }).ToList(); return value; } catch (Exception e) { Debug.WriteLine($"Error:{e}"); return null; } }</pre><p> 我创建了一个使用 orderId 返回键值的方法,但我仍然无法访问列表的值,在这种情况下,这将是发送列表时以自动增量方式生成的对象</p><p><a href="https://i.stack.imgur.com/ENEas.png" rel="nofollow noreferrer">图 2</a></p></div></object> - How can I get a key from a List <object> in Firebase in Xamarin.Forms?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM