使用CollectionView中的ItemTemplate绑定Xamarin Forms 4(前9)的问题

问题描述 投票:0回答:1

要自定义CollectionView中特定项的外观,我使用DataTemplateSelector在运行时根据数据绑定属性的值选择DataTemplate。但是,与ListView中发生的情况不同,数据绑定似乎不适用于CollectionView中的ItemTemplate。

我已经使用ListView测试了我的解决方案而不是CollectionView,它可以工作。如果我用内联ItemTemplate替换资源ItemTemplate绑定,一切正常。

我正在尝试自定义从ISensor继承的不同对象。看起来像

public interface ISensor
{
    string Name { get; set; }
    // ...
}

这是视图模型:

public class TestViewModel : MvxNavigationViewModel
{
    private static ObservableCollection<ISensor> _SensorList;

    public TestViewModel(IMvxLogProvider logProvider, IMvxNavigationService navigation)
        : base(logProvider, navigation)
    {
        _SensorList = new ObservableCollection<ISensor> { new Sensor("Thermostat"), null };
    }

    public ObservableCollection<ISensor> SensorsSource { get => _SensorList; }
}

这是包含CollectionView的页面:

<ContentView>
    <StackLayout>
        <CollectionView ItemsSource="{Binding SensorsSource}" ItemTemplate="{StaticResource SensorsTemplate}" Margin="10">
            <CollectionView.ItemsLayout>
                <GridItemsLayout Orientation="Vertical" Span="2"/>
            </CollectionView.ItemsLayout>

            <CollectionView.EmptyView>
                <StackLayout>
                    <Label Text="Add a new sensor"/>
                </StackLayout>
            </CollectionView.EmptyView>
        </CollectionView>

    </StackLayout>
</ContentView>

DataTemplateSelector:

public class SensorSelector : DataTemplateSelector
{
    public DataTemplate EmptyTemplate { get; set; }
    public DataTemplate SensorTemplate { get; set; }

    protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
    {
        if (item is Sensor)
            return SensorTemplate;
        return EmptyTemplate;
    }
}

App.xaml文件中的DataTemplate:

<DataTemplate x:Key="EmptyDataTemplate">
    <ViewCell>
        <StackLayout BackgroundColor="Yellow">
            <Label Text="EMPTY"/>
        </StackLayout>
    </ViewCell>
</DataTemplate>
<DataTemplate x:Key="SensorDataTemplate">
    <ViewCell>
        <StackLayout BackgroundColor="Red">
            <Label Text="{Binding Name}"/>
        </StackLayout>
    </ViewCell>
</DataTemplate>
<Selectors:SensorSelector x:Key="SensorsTemplate" 
                          EmptyTemplate="{StaticResource EmptyDataTemplate}"
                          SensorTemplate="{StaticResource SensorDataTemplate}"/>

每次我进入TestViewModel时,应用程序都会崩溃。它是一个绑定错误还是我做错了什么?

xamarin.forms binding collectionview itemtemplate
1个回答
0
投票

使用ListView,用作ItemTemplate的DataTemplate的子项必须是ViewCell(或从中派生)。使用CollectionView,您无法使用ViewCell。换句话说,您不能同时使用同时适用于ListView和CollectionView的DataTemplate。在使用CollectionView时,删除DataTemplates中的ViewCell图层应修复崩溃:

<DataTemplate x:Key="EmptyDataTemplate">
    <StackLayout BackgroundColor="Yellow">
        <Label Text="EMPTY"/>
    </StackLayout>
</DataTemplate>

以及SensorDataTemplate的等效更改。

© www.soinside.com 2019 - 2024. All rights reserved.