quintendc
quintendc

Reputation: 97

Xamarin forms binding to viewmodel from listview

I have a listview that is binded to a bindingList from my viewModel, so i can use the property names from the model, but how can i bind to a property from the viewmodel again inside my listview?

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Finance.Pages.ItemsPage"
             xmlns:conv="clr-namespace:Finance.Converters"
             x:Name="Page">
    <ContentPage.Resources>
        <ResourceDictionary>
            <conv:ItemTypeNameToStringConverter x:Key="ItemTypeNameToStringConverter" />
            <conv:ColumnToColorConverter x:Key="ColumnToColorConverter" />
        </ResourceDictionary>
    </ContentPage.Resources>
    
    <ContentPage.Content>
        <StackLayout Padding="10,10">

            <StackLayout Orientation="Horizontal">
                <Label Text="Compound Items:"></Label>
                <CheckBox IsChecked="{Binding CompoundItems}"></CheckBox>
            </StackLayout>

            <ListView ItemsSource="{Binding Items}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <ViewCell.ContextActions>
                                <MenuItem Text="Edit" Command="{Binding Path=EditItemCommand}" CommandParameter="{Binding .}"/>
                                <MenuItem Text="Delete" Command="{Binding DeleteItemCommand}" CommandParameter="{Binding .}"/>
                            </ViewCell.ContextActions>
                            <StackLayout Orientation="Horizontal" >
                                <Label Text="{Binding Name, Converter={StaticResource ItemTypeNameToStringConverter}}" HorizontalOptions="StartAndExpand"/>

                                <Label Text="{Binding Count}" BindingContext="{x:Reference Name=Page}" IsVisible="{Binding CompoundItems}" HorizontalOptions="StartAndExpand"/>

                                <Label Text="{Binding Amount}" TextColor="{Binding Destination, Converter={StaticResource ColumnToColorConverter}}"></Label>
                            </StackLayout>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </StackLayout>



    </ContentPage.Content>
</ContentPage>

the property CompoundItems is a boolean from my viewmodel.

Thanks in advance,

Upvotes: 2

Views: 1137

Answers (1)

Matej Pavlů
Matej Pavlů

Reputation: 106

you can either do:

IsVisible="{Binding BindingContext.CompoundItems, Source={x:Reference Name=Page}}"

Or use relativesource to get to parents BindingContext

<Label Text="{Binding Count}" IsVisible="{Binding CompoundItems, Source={RelativeSource AncestorType={x:Type local:YourViewModelType}}}"/>

Upvotes: 3

Related Questions