【问题标题】:Is it possible to write some logic for a viewcell and get a value from this this viewcell field?是否可以为 viewcell 编写一些逻辑并从此 viewcell 字段中获取值?
【发布时间】:2019-01-06 18:21:55
【问题描述】:

是否可以用ViewCells 创建一个ListView,其中包含两个ButtonsLabel,第一个按钮是“+”,第二个是“-”,标签是一个计数器,显示点击了多少“+”按钮。

然后我希望能够从我的列表视图中获取绑定到此视图单元的项目以及有关已选择该项目的信息。

现在我创建了一个StackLayout,里面装满了Views,这就是“模拟”Viewcells。这个解决方案对很多项目都非常不利,因为我必须创建很多 Views(需要几秒钟)。

所以我想使用ListView 解决问题,但我不知道如何实现。或者,也许您有比使用列表视图更好的解决方案?

【问题讨论】:

    标签: c# listview xamarin xamarin.forms datatemplate


    【解决方案1】:

    这应该是微不足道的。首先,创建一个数据结构来保存您的数据

    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; }
    

    您需要使用尽可能多的行来初始化它,以便在列表中显示。使用绑定到您的 Count 属性的标签和按钮创建模板

    <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>
    

    在您的代码隐藏中

    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++;
    }
    

    最后,使用绑定或者直接赋值来设置List的ItemsSourcee

    listView.ItemsSource = data;
    

    【讨论】:

    • 但我不想使用步进器。我想使用两个样式按钮
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 2018-07-07
    • 1970-01-01
    • 2016-08-25
    • 2017-06-18
    • 2021-04-05
    • 1970-01-01
    相关资源
    最近更新 更多