Кнопка привязки в шаблоне данных C# - PullRequest
0 голосов
/ 22 марта 2020

Я пытаюсь привязать кнопку в шаблоне данных, который используется представлением коллекции. Это моя кнопка внутри DataTemplate, и я хочу связать ее с командой в DetailDayPageViewModel.

        Button viewComment = new Button()
        {
            TextColor = Color.DodgerBlue,
            HorizontalOptions = LayoutOptions.Start,
            VerticalOptions = LayoutOptions.Start,
            FontSize = 16
        };
        // this binding does not work
        viewComment.SetBinding(Button.CommandProperty, nameof(DetailDayPageViewModel.ViewComment));

Ответы [ 2 ]

0 голосов
/ 22 марта 2020

Используйте RelativeBinding для привязки значений BindingContext страницы к свойству внутри DataTemplate.

Это можно сделать двумя способами:

1: привязка через ViewModel. ReltiveBinding режима FindAncestorBindingContext

public class ItemView : Grid
{
    public ItemView()
    {
        Button clickButton = new Button() { Text = "Hi there" };
        clickButton.SetBinding(
            Button.CommandProperty,
            new Binding(
                "ItemClickCommand",
                source: new RelativeBindingSource(
                    RelativeBindingSourceMode.FindAncestorBindingContext,
                    typeof(ViewModel))
                ));

        this.Children.Add(clickButton);
    }
}

2: привязка через родительское представление BindingContext:

public class ItemView : Grid
{
    public ItemView()
    {
        Button clickButton = new Button() { Text = "Hi there" };
        clickButton.SetBinding(
            Button.CommandProperty,
            new Binding(
                "BindingContext.ItemClickCommand",
                source: new RelativeBindingSource(
                    RelativeBindingSourceMode.FindAncestor,
                    typeof(CollectionView))
                ));

        this.Children.Add(clickButton);
    }
}

Пожалуйста, проверьте и посмотрите, поможет ли это !! Комментарий к любым запросам.

0 голосов
/ 22 марта 2020

Я думаю, что вы можете взглянуть на этот пример:

TestBinding

Это относится к ListView, но его следует применить к CollectionView.

Вам необходимо установить «источник»:

        TapGestureRecognizer tgrUpDown2 = new TapGestureRecognizer();
        tgrUpDown2.SetBinding(TapGestureRecognizer.CommandProperty, new Binding("BindingContext.UpDown2Command", source: this));
        tgrUpDown2.SetBinding(TapGestureRecognizer.CommandParameterProperty, ".");

, тогда в вашей модели вы получите «параметр» passend ...

  this.UpDown2Command = new Command(async (object obj) =>
        {

            try
            {
                if (_isTapped)
                    return;

                if (obj != null)
                    System.Diagnostics.Debug.WriteLine("Obj is not null");
                else
                    System.Diagnostics.Debug.WriteLine("Obj IS null");


                _isTapped = true;

                int idx = List.IndexOf((Model)obj);

                List[idx].Checked1 = !List[idx].Checked1;

                _isTapped = false;

            }
            catch (Exception ex)
            {
                _isTapped = false;
                await Application.Current.MainPage.DisplayAlert("Attention", ex.Message, "Ok");
            }
        });

Это полезную ссылку я нашел несколько лет go:

listview-in-xamarin-forms-in-mvvm

Если вы хотите, чтобы "класс" определялся Ваш ViewCell, вы можете назначить класс следующим образом:

        lv.ItemTemplate = new DataTemplate(() =>
        {
            return new MyViewCell(lv);
        });

Где MyViewCell - что-то вроде:

    class MyViewCell : ViewCell
    {

        public MyViewCell(ListView lv)
        {
            StackLayout slView = new StackLayout();
            slView.SetBinding(StackLayout.BackgroundColorProperty, "BackgroundColor");

            Label lDesc = new Label();
            lDesc.SetBinding(Label.TextProperty, "Description", stringFormat: "DESCRIPTION: {0}");
            lDesc.SetBinding(Label.TextColorProperty, "TextColor");

            // LABEL QTY
            TapGestureRecognizer tgrQty = new TapGestureRecognizer();
            tgrQty.SetBinding(TapGestureRecognizer.CommandProperty, new Binding("BindingContext.QtyCommand", source: lv));
            tgrQty.SetBinding(TapGestureRecognizer.CommandParameterProperty, ".");

.... ....

            View = slView;

        }

    }

Вы можете передать ListView в конструкторе, чтобы использовать его в свойстве связывания «source».

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