Persego
Persego

Reputation: 15

Xamarin need as commandParameter the select item from an element from the same xaml

I'm new to xamarin and I need to develop an app for homework.

As stated in the title I need to pass as CommandParameter in a button, the SelectedItem from a Picker that is in the same Page.xaml.

As stated in other posts I tried Binding with RelativeSource, but it doesn´t work so I came here searching for an answer, cause I can't find a way to do it correctly.

My actual code is this

<StackLayout Spacing="20" Padding="15">
    <Label Text="Text:" FontSize="Medium" />
    <Label Text="{Binding Material.Name}" d:Text="Item name" FontSize="Small"/>
    <Label Text="Description:" FontSize="Medium" />
    <Label Text="{Binding Material.Description}" d:Text="Item description" FontSize="Small"/>

    <Picker x:Name="PocketSelector"
            Title="--Select--"
            ItemsSource="{Binding Pockets}"
            ItemDisplayBinding="{Binding PocketName}"
            SelectedItem="SelectedPocketName"/>

    <Button x:Name="AddToButton"
            Text="Add To"
            Command="{Binding AddToPocketCommand}"
            CommandParameter="{Binding Source={RelativeSource Picker}, Path=Picker.SelectedItem}"/>
</StackLayout>

I'm currently using a MVVM pattern

I dont need changes in the ViewModel or something like that, just a way to pass the selectedItem element as parameter in my button.

Thank you in advance

Upvotes: 1

Views: 2888

Answers (1)

Harikrishnan
Harikrishnan

Reputation: 1474

Below code should work fine.

<StackLayout Spacing="20" Padding="15">
    <Label Text="Text:" FontSize="Medium" />
    <Label Text="{Binding Material.Name}" d:Text="Item name" FontSize="Small"/>
    <Label Text="Description:" FontSize="Medium" />
    <Label Text="{Binding Material.Description}" d:Text="Item description" FontSize="Small"/>

    <Picker x:Name="PocketSelector"
        Title="--Select--"
        ItemsSource="{Binding Pockets}"
        ItemDisplayBinding="{Binding PocketName}"
        SelectedItem="SelectedPocketName"/>

    <Button x:Name="AddToButton"
        Text="Add To"
        Command="{Binding AddToPocketCommand}"
        CommandParameter="{Binding SelectedItem, Source={x:Reference PocketSelector}}"/>
</StackLayout>

Upvotes: 2

Related Questions