Forum Xamarin Xamarin.Forms

BUG - CustomViewCell with CustomBehavior - Value is set on multiple editors

MigokMigok Member ✭✭

Problem noticed only on android.
When I set a value to an editor, the same value is also set on other editor of the listview, when you scrolldown.

  • Create a listview
  • Set a custom DataTemplate
  • Create dynamic editors on the DataTemplate
  • Set a Behavior to the editors : editor MUST have custom Keyboard, or bug wont appear.
  • Bug when you set a value on an editor.

MainPage.xaml

<ListView 
        x:Name="list"
        HasUnevenRows="True"
        SelectionMode="None"
        />

MainPage.xaml.cs

List<string> l = new List<string> { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
list.ItemsSource = l;
list.ItemTemplate = new DataTemplate(typeof(ViewCellTest));

ViewCellTest.xaml

<ViewCell.View>
      <StackLayout x:Name="stack">
            <Label Text="{Binding .}" />
        </StackLayout>
  </ViewCell.View>

ViewCellTest.xaml.cs

public ViewCellTest()
        {
            InitializeComponent();

            Editor curView1 = new Editor();
            Editor curView2 = new Editor();

            curView1.Behaviors.Add(new EditorBehaviorTest());
            curView2.Behaviors.Add(new EditorBehaviorTest());

            stack.Children.Add(curView1);
            stack.Children.Add(curView2);
        }

EditorBehaviorTest.cs

class EditorBehaviorTest : Behavior<Editor>
    {
        public EditorBehaviorTest()
        {
        }

        protected override void OnAttachedTo(Editor entry)
        {
            entry.TextChanged += OnEntryTextChanged;
            entry.Keyboard = Keyboard.Telephone;
            base.OnAttachedTo(entry);
        }

        protected override void OnDetachingFrom(Editor entry)
        {
            entry.TextChanged -= OnEntryTextChanged;
            base.OnDetachingFrom(entry);
        }

        private void OnEntryTextChanged(object sender, TextChangedEventArgs args)
        {
            if (!string.IsNullOrWhiteSpace(args.NewTextValue))
            {
                bool isValid = true;

                //do some controls

                ((Editor)sender).Text = isValid ? args.NewTextValue : args.NewTextValue.Remove(args.NewTextValue.Length - 1);
            }
        }

    }

Posts

Sign In or Register to comment.