Xamarin находит ячейку просмотра, в которой мой объект находится как текстовый текст - PullRequest
0 голосов
/ 10 октября 2018

У меня есть ListView, который заполняется через dataBinding, и его viewCells настраиваются через DataTemplateSelector.

мой ListView выглядит так:

<ListView x:Name="PuzzlesContainer"
          ItemsSource="{x:Static gameBrain:GameItems.Puzzles}"
          RowHeight="167"
          ItemTemplate="{StaticResource PuzzleDataTemplateSelector}"/>

Тогда в какой-то момент я получу модификациюв одной Головоломке, которая должна быть представлена ​​линиями, нарисованными на холсте, который находится на его viewCell (из DataTemplate)

Как я могу получить доступ к ViewCell, который имеет мою головоломку как DataContext, чтобы иметь возможность вручную обновлять Canvas??

1 Ответ

0 голосов
/ 10 октября 2018

Создайте пользовательский элемент управления, полученный из ViewCell, для вас внутри вашего списка.В xaml у вас будет шаблон, в коде - здесь вы будете устанавливать значение без привязки xaml к данным.Это будет обновляться быстрее.В теории вам не понадобится выбор шаблона, так как в коде позади вы можете делать все с вашей ячейкой.Ваш класс сотовой связи:

            private INotifyPropertyChanged _oldBindingContext;

//this normally fires when you set your list ItemsSource
            protected override void OnBindingContextChanged()
            {
                if (_oldBindingContext != null)
                {
                    _oldBindingContext.PropertyChanged -= OnBindingContextPropertyChanged;
                }

                if (BindingContext != null)
                {
                    INotifyPropertyChanged ctx = null;
                    try
                    {
                        ctx = (INotifyPropertyChanged)BindingContext;
                    }
                    catch
                    {
                        base.OnBindingContextChanged();
                        return;
                    }
                    ctx.PropertyChanged += OnBindingContextPropertyChanged;
                }
                _oldBindingContext = (INotifyPropertyChanged)BindingContext;
                OnCellBindingContextChanged();
                base.OnBindingContextChanged();
            }

            public virtual void OnCellBindingContextChanged()
            {
            if (BindingContext == null) return;

            //update your xaml here.

            var model = (MyItemCLass)BindingContext;
            MyXamlTextBox.Text = model.Title;


            }

    //you are left with the challenge to call dispose manually when your page destroys. 
    //im calling this from my custom list for every cell when page pops up
            public void Dispose()
            {
                if (BindingContext != null)
                {
                    INotifyPropertyChanged ctx = null;
                    try
                    {
                        ctx = (INotifyPropertyChanged)BindingContext;
                        ctx.PropertyChanged -= OnBindingContextPropertyChanged;
                    }
                    catch
                    {
                    }
                }           
            }

            //and this is what your question is about:
            //when a single property of your model changes we land here to react
            private void OnBindingContextPropertyChanged(object sender, PropertyChangedEventArgs e)
            {                        
                if (e== null || BindingContext==null) return;
    var = PropertyName = e?.PropertyName;
    //todo more checks

                var propertyInfo = BindingContext.GetType().GetProperty(propertyName);
                if (propertyInfo == null) return;

                if (propertyName == "IsFavorite")
                {
                    UpdateFav((MySupaItem)BindingContext);
                }

    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...