the_tr00per
the_tr00per

Reputation: 439

Xamarin Forms ListVew Binding - Bind ViewCell Label to a Method

I'm using Xamarin Forms using an MVVM approach and it works well.

I need a add functionality to an existing ListView to display text when the bound value is a certain value.

Here is the cell that generates the description

   <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout>
                    <Label Text="{Binding Description}"  x:Name="lblDescription" 
               Style="{DynamicResource ListItemTextStyle}" />
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>

Is there any way of basically only displaying the label is the following function is true (this could be in the view model or code behind) for example:

private bool IsDescriptionOk(string description)
    {
       //Look up description possibly in another lookup list
    }

id want to bind the visible to the method like:

Visible="{Binding IsDescriptionOk}"

But as its in the List View, id need to pass in the item index if that makes sense?

Upvotes: 0

Views: 657

Answers (2)

Jason
Jason

Reputation: 89082

private string _description = null;

public string Description {
  get {
    if (_description == null) {
      // method to fetch/build description 
      _description = GetDescription();
    }
    return _description;
  }

public bool IsDescriptionOK {
  get {
    if ((Description == "Online") || (other values here...)) return false;
    return true;
  }
}

Upvotes: 0

EvZ
EvZ

Reputation: 12169

I guess there could be multiple ways of solving this kind of issues. One of them could be to use IValueConverter. Something like this:

<ViewCell>
    <StackLayout>
        <Label
            Text="{Binding Description}"
            Style="{DynamicResource ListItemTextStyle}"
            IsVisible="{Binding Description, Converter="{StaticResource ItemStatusToVisiblityConverter}" />
    </StackLayout>
</ViewCell>

However, I think that the List should contain only visible items, otherwise you may have multiple empty ListItems.

Upvotes: 1

Related Questions