Xamarin Custom Control Command / CommandParameter 问题

Xamarin Custom Control Command / CommandParameter question

一段时间以来,我一直致力于创建自定义控件。经过几次迭代后,我得出的结论是我遇到了一个绑定问题......事实上,当我将控件放入一个简单的 XAML 页面并执行该功能时,它工作得很好。但是,当我需要在单个页面上实例化大量控件时,即放入集合、flexlayout、carouselview 时,Command 和 CommandParameter 绑定会丢失...并且 ViewModel 调用不再发生。

我的控件很简单...想到一个复选框替换。我放置了一个 1x1 网格,带有一个框架(用于轮廓)和一个用于放置单个字符的标签..."A"、"B"、"C"...“1”。 “2”。 “3”...无论您需要什么...我都有可绑定的属性...Text、TextColor、BorderColor、BackgroundColor 和 "Selected"。

所以,现在我需要一个页面来提问... "How do you feel about... whatever... Pick all that apply." 然后我提供一个列表...带有数字或字母的项目...用户可以 select none, any, or all...所以我创建了一个包含一系列问题的视图,其中包含 "checkable" 项的列表...正如我上面所说,如果控件在一个独立的页面...如果我动态生成这些控件的列表,Command 和 CommandParameter 突然不再工作。

我的测试实现看起来像下面这样...尽管在这种情况下,想想更简单的东西,比如 "lottery ticket" 数字选择器。在这种情况下,ViewModel 将有一个简单的 ObservableCollection<string> PrimaryControlList;,并且 CommandParamter 将调用 VM 函数以及控件的文本,以跟踪用户已经 select 编辑的项目。

                <Frame x:Name="primaryFrame">
                <FlexLayout x:Name="flexPrimary" BindableLayout.ItemsSource="{Binding PrimaryControlList}" Wrap="Wrap" Direction="Row" JustifyContent="SpaceAround" AlignItems="Start" AlignContent="Start" >
                    <BindableLayout.ItemTemplate>
                        <DataTemplate>
                            <local:NumberSelect Text="{Binding .}" Command="Binding DoSomethingWithThis" CommandParameter="{Binding .}"/>
                        </DataTemplate>
                    </BindableLayout.ItemTemplate>
                </FlexLayout>
            </Frame>

谁能指导一下?

命令在您的ViewModel中,而FlexLayout的当前BindingContextPrimaryControlList

解决方案:

首先,给你的ContentPage起个名字,让我们说吧MyPage:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"

             x:Name="MyPage"

             x:Class="App266.MainPage">

假设您的页面绑定到 ViewModel 并且您的命令绑定应该是:

<local:NumberSelect Text="{Binding .}" Command="{Binding BindingContext.ButtonCommand, Source={x:Reference MyPage}}" CommandParameter="{Binding .}"/>