Xamarin Forms 中数据模板视图单元内的绑定上下文

Gil*_*and 5 c# data-binding binding xamarin xamarin.forms

我在列表视图中显示了一个自定义单元格。它应该工作,但我担心它有效,我不明白为什么。

让我为您安排一下,因为它有点复杂。

基本上,我在顶部显示一个带有搜索字段的联系人列表。我还有其他各种要显示的内容超出了这个问题的范围,但为了清楚起见,您将在整个代码中看到它们,特别是在 xaml 和数据模板选择器中。

我使用不同类型的自定义单元格来显示我的联系人列表的每个部分(有一个标题单元格、一个搜索单元格等等)。

在这里,ContactsPage持有列表视图和数据模板的声明。

<ContentPage>
    <ContentPage.Resources>
        <ResourceDictionary>


            <DataTemplate x:Key="HeaderTemplate">
                <ViewCell>
                    <StackLayout>
                        <local:HeaderView/>    
                    </StackLayout>
                </ViewCell>
            </DataTemplate>


            <DataTemplate x:Key="SearchTemplate">
                <local:SearchCell/>                 //<=== Important
            </DataTemplate>


            <DataTemplate x:Key="CategoryTemplate">
                <ViewCell
                    x:Name="CategoryCell">
                    <Label
                        Text="CategoryCell" ></Label>
                </ViewCell>
            </DataTemplate>


            <DataTemplate x:Key="SelectionTemplate">
                <ViewCell
                    x:Name="SelectionCell">
                    <Label
                        Text="Selection Cell" ></Label>
                </ViewCell>
            </DataTemplate>


            <DataTemplate x:Key="ContactTemplate">
                <ViewCell
                    x:Name="ContactCell">
                    <Label
                        Text="{Binding FirstName}" ></Label>
                </ViewCell>
            </DataTemplate>

            <local:ContactDataTemplateSelector x:Key="TemplateSelector"
                                              HeaderTemplate="{StaticResource HeaderTemplate}"
                                              SearchTemplate="{StaticResource SearchTemplate}"
                                              CategoryTemplate="{StaticResource CategoryTemplate}"
                                              SelectionTemplate="{StaticResource SelectionTemplate}"
                                              ContactTemplate="{StaticResource ContactTemplate}"/>
        </ResourceDictionary>
    </ContentPage.Resources>
Run Code Online (Sandbox Code Playgroud)

你看我有各种数据模板,每个模板都有自己的用途。Header 正在工作,其余的正在进行中,我唯一关心的是Search 的实现。从单元格到视图模型,再到数据模板。

现在这只是资源,这是实际的页面 UI(仅相关代码)

<ContentPage.Content>
   ... Content of the page, including the actual listview
            <ListView 
                x:Name="ContactsListView"
                HasUnevenRows="True""
                ItemTemplate="{StaticResource TemplateSelector}"
                ItemsSource="{Binding ListSource}">
            </ListView>
    </ContentPage.Content>
Run Code Online (Sandbox Code Playgroud)

让我在该视图的视图模型中带您了解这背后的逻辑之旅。视图本身的代码隐藏本身什么都不做,这里是该联系人列表的 ViewModel。

public class ContactsViewModel : BaseViewModel, IContactsViewModel
    {
        readonly IContactsService _service;
        List<object> _listSource;

        public List<object> ListSource
        {
            get => _listSource;
            private set
            {
                _listSource = value; 
                OnPropertyChanged();
            }
        }

        public string CurrentText => "HelloX";             //<=== Important
        readonly ISearchViewModel _searchViewModel;
        readonly ICategoryFilterViewModel _categoryFilterViewModel;
        readonly ISelectionViewModel _selectionViewModel;

        public ContactsViewModel()
        {
            _service = new();

            HeaderViewModel = new HeaderViewModel();

            _searchViewModel = new();
            _categoryFilterViewModel = new();
            _selectionViewModel = new();

            ListSource = GenerateDefaultList();
        }

        public async Task LoadContacts()       //Called when UI appears.
        {
            await _service.LoadContacts();

            var list = GenerateDefaultList();
            list.AddRange(_service.Contacts);

            ListSource = list;
        }

        List<object> GenerateDefaultList()
        {
            return new List<object>()
            {
                HeaderViewModel,
                _searchViewModel,              //<===== important
                _categoryFilterViewModel,
                _selectionViewModel
            };
        }
    }
Run Code Online (Sandbox Code Playgroud)

为了清楚起见,我包含了大部分代码;这里我想强调的重要部分是ListSource里面已经有一些视图模型。我正在使用该源来填充我的列表视图,对象类型定义了我将使用的数据模板类型。这是在 DataTemplate 选择器中完成的,它在这里:

public class ContactDataTemplateSelector : DataTemplateSelector
    {
        public DataTemplate ContactTemplate { get; set; }
        public DataTemplate HeaderTemplate { get; set; }
        public DataTemplate SearchTemplate { get; set; }
        public DataTemplate CategoryTemplate { get; set; }
        public DataTemplate SelectionTemplate { get; set; }

        protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
        {            
            switch (item)
            {
                case HeaderViewModel _:
                    return HeaderTemplate;
                case SearchViewModel _:
                    return SearchTemplate;            //<==== important
                case CategoryFilterViewModel _:
                    return CategoryTemplate;
                case SelectionViewModel _:
                    return SelectionTemplate;
                default:
                    return ContactTemplate;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

所以我确实有一个SearchViewModel(对我的问题很重要的唯一一个)的实例,但它从未在任何地方说搜索数据模板的 ViewCell 实际上使用了 SearchViewModel。我只是将它用作我if声明的条件。

这是数据模板中使用的搜索单元格(它本身是用数据模板选择器选择的)

<ViewCell x:Class="MYNAMESPACE.SearchCell">
    <AbsoluteLayout>
        <Frame>
            <StackLayout>
                <Entry
                    Placeholder="{Binding PlaceHolderText}"/>
                <Button
                    Text="{Binding CurrentText}"
                    Command="{Binding SearchCommand}"/>
            </StackLayout>
        </Frame>
    </AbsoluteLayout>
</ViewCell>
Run Code Online (Sandbox Code Playgroud)

我尽可能多地删除,而不会冒着模糊上下文的风险。我知道这是一堵代码墙,但我相信如果您决定进行调查,它会很有用。

根据我的理解,我从来没有为我的自定义 ViewCell(搜索单元)提供绑定上下文。我确实在里面有绑定,特别是,我的工作示例是CurrentText. 我有它作为我的文字SearchViewModel

public class SearchViewModel : ISearchViewModel
    {
        public string CurrentText => "<TODO SEARCH>";     //<=== Important

        //NotifyPropertyChanged Implementation
    }
Run Code Online (Sandbox Code Playgroud)

我有另一个CurrentTextin ContactsViewModel,但在运行时显示的文本是来自SearchViewModel. 我看到的是“”而不是“HelloX”。这就是我要的。我只是不明白单元格如何/为什么使用我的视图模型。

我只使用视图模型来选择要显示的数据模板,没有将该视图模型设置为该数据模板的绑定上下文,也没有设置视图单元格。还是我?绑定上下文来自哪里?

小智 4

感谢您提出详细的问题,我很确定我正在遵循您所做的事情,所以希望这会有所帮助:

如果没有另外指定,页面上每个元素的 BindingContext 都是根据其父元素设置的。我确信您可能已经看到,当您为页面设置 BindingContext 时,它会向下流动到该页面的所有元素,除非您显式覆盖它。因此,对于列表,每个项目的 BindingContext 会自动设置为其相应的 ItemsSource 对象。因此,当您从模板选择器返回 SearchTemplate 时,它​​的所有元素都将继承该项目的绑定上下文,在本例中是您在GenerateDefaultList 期间创建并放入ListSource 的SearchViewModel 实例。