【问题标题】:Modify label text on click in listview在列表视图中单击时修改标签文本
【发布时间】:2017-04-08 01:22:47
【问题描述】:

这是我的代码:

 public partial class MyGS: ContentPage {
   private GestioneSchedeViewModel _viewModel;
   
   public MyGS() {
     InitializeComponent();
     BindingContext = _viewModel  = new MyGSViewModel();
   }

  private void modifySch(object sender, EventArgs e)
   {
     SchedeItem item = (SchedeItem)((Image)sender).BindingContext;
     if (item == null) { return; }
     _viewModel.modifyItem(item.realm_id, item.list_id);
   }
  }

  public class MyGSViewModel: INotifyCollectionChanged {
   public event NotifyCollectionChangedEventHandler CollectionChanged;

   public ObservableCollection < SchItem > Items {get;private set;}

   public MyGSViewModel() {
    Items = new ObservableCollection<SchItem>();
    //Item Population 
   }

   public void modificaItem(int rid, int lid)
    {
      SchedeItem myItem = Items[lid];
      myItem.name = "New Text";
    }

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

   }

   public class SchItem : INotifyPropertyChanged {
     public int realm_id {get;set;}
     public int list_id {get;set;}
     public int name {get;set;}

     public event PropertyChangedEventHandler PropertyChanged;

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

}

如何在图像单击时更改列表视图中与名称绑定的标签文本?目前,点击不会改变,列表视图的目标项目中没有显示“新文本”。

注意:XAML here

注意:在 Android 设备中调试

【问题讨论】:

  • 如果要修改 SchItem 的属性,那么该类需要实现 INotifyPropertyChanged
  • 在 SchItem 类中实现 INotifyPropertyChanged 不起作用
  • 你的实现正确吗?
  • @Jason 我已经更新了问题,请告诉我
  • @Segamoto nop,不正确 ;-)

标签: listview xamarin viewmodel observablecollection inotifypropertychanged


【解决方案1】:

您必须在每个属性的设置器中执行 OnPropertyChanged() 方法,以便通知绑定并“刷新”文本。

    private string name;

    public string Name
    {
        get
        {
            return name;
        }
        set
        {
            if (name == value)
            {
                return;
            }
            name = value;
            OnPropertyChanged();
        }
    }

不要忘记更新绑定路径以使用属性而不是私有字段...({Binding Name})

【讨论】:

    猜你喜欢
    • 2015-12-03
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多