Search code examples
c#listviewxamarinxamarin.formsdatatemplate

Is it possible to write some logic for a viewcell and get a value from this this viewcell field?


Is it possible to create a ListView with ViewCells that will contain two Buttons and Label, first button will be "+", second "-" and a label will be a counter that will show how much "+" button has been tapped.

Then I want to be able to get from my listview an item that is binded to this viewcell and information about how much this item has been selected.

For now I created a StackLayout filled with Views thats "mocks" a Viewcells. This solution is so bad for many items because I have to create lots of Views (it takes few seconds).

So I would like to solve the problem using a ListView but I have no idea how to achive this. Or maybe you have a better solution than using a listview?


Solution

  • this should be trivial. First, create a data structure to hold your data

    public class MyData : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;  
    
        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")  
        {  
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        } 
    
      private double _count;
      public double Count 
      { 
        get
        { return _count; }
        set
        { 
          _count = value;
          NotifyPropertyChanged();
        }
    }
    
    List<MyData> data { get; set; }
    

    you will need to initialize it with as many rows as your want to display in your list. The create a template with a Label and Buttons that are bound to your Count property

    <ListView x:Name="listView" >
      <ListView.ItemTemplate>
        <DataTemplate>
          <ViewCell>
            <StackLayout>
              <Label Text="{Binding Count}" />
              <Button Clicked="Increment" CommandParameter="{Binding .}" Text="+" />
              <Button Clicked="Decrement" CommandParameter="{Binding .}" Text="-" />            
            </StackLayout>
          </ViewCell>
        </DataTemplate>
      </ListView.ItemTemplate>
    </ListView>
    

    in your code-behind

    protected void Decrement(object sender, EventArgs args) {
      var b = (Button)sender;
      var data = (MyData)b.CommandParameter;
      data.Count--;
    }
    
    protected void Increment(object sender, EventArgs args) {
      var b = (Button)sender;
      var data = (MyData)b.CommandParameter;
      data.Count++;
    }
    

    finally, use binding or direct assignment to set the List's ItemsSourcee

    listView.ItemsSource = data;