Access page bindingContext within ListView itemTemplateSelector


#1

I’m building a comment thread using ListView. I want to use a different ListView.itemTemplate if the comment being bound was created by the current user.

Each “comment” has a ‘UserID’ property. I need to check if this property matches another that I have bound to the page.bindingContext (user.UserID).

Within the ListView I can access user.UserID using:

$parents['Page'].user.UserID, $parents['Page'].user.UserID

Is there any way I can I access this property within itemTemplateSelector in order to compare with the current comment.UserID?

I tried:

itemTemplateSelector="$parents['Page'].user.UserID, UserID == $parents['Page'].user.UserID ? 'align-right' : 'align-left'"

but obviously UserID is now out of scope so the expression always returns false.

JS

pageData.user = {
    'UserID': 1
}

var comments = [{
    'UserID': 1,
    'text': 'Lorem ipsum 1.'
},
{   
    'UserID': 2,
    'text': 'Lorem ipsum 2.'
}]

pageData.set('comments', comments);

page.bindingContext = pageData;

XML

<ListView id="listViewComments" items="{{ comments }}" itemTap="listViewItemTap" itemTemplateSelector="$parents['Page'].user.UserID, UserID == $parents['Page'].user.UserID ? 'align-right' : 'align-left'">
    <ListView.itemTemplates>

        <template key="align-left">
            <GridLayout columns="26, auto" class="comment-item">
                <Image col="0" src="~/img/demo-user.jpg" />  
                <StackLayout col="1">
                    <Label textWrap="true" text="{{ text }}" />
                </StackLayout>
            </GridLayout>  
        </template>
        <template key="align-left">
            <GridLayout columns="auto, 26" class="comment-item">
                <Image col="1" src="~/img/demo-user.jpg" />  
                <StackLayout col="0">
                    <Label textWrap="true" text="{{ text }}" />
                </StackLayout>
            </GridLayout>  
        </template>

    </ListView.itemTemplates>
</ListView>

#2

Since the items property isn’t out of scope on your ListView, neither should itemTemplateSelector be. Also, you are passing an expression without double curly brackets. Try wrapping your expression like this:

itemTemplateSelector="{{ user.UserID, UserID == user.UserID ? 'align-right' : 'align-left' }}"

UPDATE
On a second note, I don’t think what you’re trying to achieve is possible since you don’t have access to the inner scope. Isn’t there a property on the Template view that either activates or deactivates depending on a specific condition?