如何在ListView中相对于外部绑定上下文设置绑定上下文?

时间:2018-09-07 18:02:17

标签: xamarin xamarin.forms

下面的代码应该使您对我正在使用的东西有一个很好的了解。每个Widget都显示在ListView中。但是有些小部件是“着火的”,我想用红色显示它们的StreetName。问题在于WidgetsViewModel中保留着哪些小部件着火的记录。

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage 
                xmlns="http://xamarin.com/schemas/2014/forms"
                xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                x:Class="SickProgram.Views.Pages.WidgetsPage"
                xmlns:ViewModels="clr-namespace:SickProgram.ViewModels">

    <ContentPage.BindingContext>
        <ViewModels:WidgetsViewModel />
    </ContentPage.BindingContext>

    <StackLayout>
        <ListView ItemsSource="{Binding Widgets}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout>
                            <Label Text="{Binding StreetName}"/>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>

</ContentPage>

完美的世界中,它看起来像:

<!- OnFire is a method in the WidgetsViewModel that takes in a widget Id and returns a color. ->
<Label Text="{Binding StreetName}" Color={Binding BindingContext.Parent.OnFire(BindingContext.Id)}/>   

此外,我认为使用所选项目不会完成任务。火警小部件的显示应独立于所选项目的显示。

1 个答案:

答案 0 :(得分:1)

我们稍后可以解决有关OnFire小部件具有单独颜色的问题。

您可以定义数据模板并使用数据模板选择器。请参阅https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/templates/data-templates/selector

列表视图要显示的每个项目都将调用选择器。是否可以通过查看对象中的某些属性来确定小部件是否处于onFire状态。这种方法会起作用。如果不让我知道还有其他想法。

对不起,我尝试格式化此帖子的输出。

相关问题