Forum Xamarin.Forms

Announcement:

The Xamarin Forums have officially moved to the new Microsoft Q&A experience. Microsoft Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

To create new threads and ask questions head over to Microsoft Q&A for .NET and get involved today.

Click Button represents SelectedItem command from ListItem

ycusoyycusoy Member ✭✭

Hi buddy,
I made 1 button and 1 group of list items. then I choose one from the list of items. how to make this button can represent the command select goods when the button is pressed. assuming as if the select item command was executed on the button.
thanks in advance for the answers given B)

Tagged:

Best Answer

  • LeonLuLeonLu Member, Xamarin Team Xamurai
    edited February 5 Accepted Answer

    Do you want to click the button outside the listview, then one of item will be selected in listview? For example, I want to select the first item in the listview when I click the outside Button.

    You can binding a command in the Button.

    <Button Text="click" Command="{Binding SelectCommand}"></Button>
    

    this first item is persons[0];, so I set selectItems = persons[0]; in the SelectCommand of viewModel,

     public class PersonViewModel: INotifyPropertyChanged
        {
    
            public event PropertyChangedEventHandler PropertyChanged;
    
            protected virtual void OnPropertyChanged(string propertyName)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
    
          //  public Person selectItems { get; set; }
    
            Person _selectItems = new Person();
            public Person selectItems
            {
                get
                {
                    return _selectItems;
                }
    
                set
                {
                    if (_selectItems != value)
                    {
                        _selectItems = value;
                        OnPropertyChanged("selectItems");
    
                    }
                }
    
            }
    
    
            public ObservableCollection<Person> persons { get; set; }
    
            public ICommand FavouriteCommand { protected set; get; }
            public ICommand SelectCommand { protected set; get; }
            public PersonViewModel()
            {
    
                FavouriteCommand = new Command<Person>(async (key) =>
                {
                    Person person = key as Person;
                    selectItems=person;
    
                });
    
                persons = new ObservableCollection<Person>();
                persons.Add(new Person() { Name = "Leon1", Count = 1, Isfavourite = false });
                persons.Add(new Person() { Name = "Leon2", Count = 2, Isfavourite = false });
                persons.Add(new Person() { Name = "Leon3",  Count = 3, Isfavourite = false });
                persons.Add(new Person() { Name = "Leon4",  Count = 4, Isfavourite = false });
                persons.Add(new Person() { Name = "Leon5",  Count = 5, Isfavourite = false });
    
                SelectCommand = new Command(() =>
                {
    
                    selectItems = persons[0];
    
                });
            }
        }
    

Answers

  • LeonLuLeonLu Member, Xamarin Team Xamurai

    Do you want to click the Button, then list item will be choose?

    If so, you can use SelectedItem="{Binding selectItems, Mode=TwoWay}" for Listview, then when you click the Button, execute the command like following code.

     <ListView x:Name="mylistview" 
                      ItemsSource="{Binding persons}"   
                      CachingStrategy="RecycleElement" 
                      SeparatorVisibility="None" 
                      HasUnevenRows="True" 
                      SelectedItem="{Binding selectItems, Mode=TwoWay}"
                      VerticalScrollBarVisibility="Always"
                      >
                <ListView.ItemTemplate>
                    <DataTemplate >
    
                        <ViewCell >
    
                            <Frame IsClippedToBounds="False" 
                                                   Margin="0,5" 
                                                   CornerRadius="10" 
                                                   Padding="0" 
                                                   HasShadow="False" 
                                                   BorderColor="#f0f0f0" 
                                                   BackgroundColor="Transparent" >
    
                                <StackLayout Padding="0" Spacing="0" MinimumHeightRequest="0">
                                    <StackLayout Orientation="Horizontal">
                                        <Label Text="{Binding Name}" Margin="13,12,5,0" FontAttributes="Bold" FontSize="18" TextColor="#222222">
    
                                        </Label>
                                        <Button 
                                                    Command="{ Binding BindingContext.FavouriteCommand, Source={x:Reference Name=mylistview} }"  
                                                    CommandParameter="{Binding .}"  />
    
                                    </StackLayout>
                                    <Label Text="{Binding Count}" Margin="13,6,0,12">
                                    </Label>
                                </StackLayout>
                            </Frame>
                        </ViewCell>
    
                    </DataTemplate>
    
                </ListView.ItemTemplate>
            </ListView>
    
    

    In the viewModel, we can achieve it by adding selectItems=person; in the Button's Command.

      public class PersonViewModel: INotifyPropertyChanged
        {
    
            public event PropertyChangedEventHandler PropertyChanged;
    
            protected virtual void OnPropertyChanged(string propertyName)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
    
            Person _selectItems = new Person();
            public Person selectItems
            {
                get
                {
                    return _selectItems;
                }
    
                set
                {
                    if (_selectItems != value)
                    {
                        _selectItems = value;
                        OnPropertyChanged("selectItems");
    
                    }
                }
    
            }
    
    
            public ObservableCollection<Person> persons { get; set; }
    
            public ICommand FavouriteCommand { protected set; get; }
    
            public PersonViewModel()
            {
    
                FavouriteCommand = new Command<Person>(async (key) =>
                {
                    Person person = key as Person;
                    selectItems=person;
    
                });
    
                persons = new ObservableCollection<Person>();
                persons.Add(new Person() { Name = "Leon1", Count = 1, Isfavourite = false });
                persons.Add(new Person() { Name = "Leon2", Count = 2, Isfavourite = false });
                persons.Add(new Person() { Name = "Leon3",  Count = 3, Isfavourite = false });
                persons.Add(new Person() { Name = "Leon4",  Count = 4, Isfavourite = false });
                persons.Add(new Person() { Name = "Leon5",  Count = 5, Isfavourite = false });
    
            }
        }
    }
    
    

    Here is running screenshot.


    Xamarin forums are migrating to a new home on Microsoft Q&A!
    We invite you to post new questions in the Xamarin forums’ new home on Microsoft Q&A!
    For more information, please refer to this sticky post.

  • ycusoyycusoy Member ✭✭
    edited February 5

    this method works very well. but I mean is location of Button is not in ListView. like the following example on xaml:

    <ListView x:Name="mylistview" ....
    ...
     </ListView>
    
    <Button Text="This Button"/>
    

    for example with a method like this for a button

    private async void OnClickButton(object sender, SelectionChangedEventArgs e)
            {
                var item = (Data)e.CurrentSelection.FirstOrDefault();
                if (e.CurrentSelection != null)
                {
                    await Navigation.PushAsync(new EditData
                    {
                        BindingContext = item
                    });
                }
            }
    
  • LeonLuLeonLu Member, Xamarin Team Xamurai
    edited February 5 Accepted Answer

    Do you want to click the button outside the listview, then one of item will be selected in listview? For example, I want to select the first item in the listview when I click the outside Button.

    You can binding a command in the Button.

    <Button Text="click" Command="{Binding SelectCommand}"></Button>
    

    this first item is persons[0];, so I set selectItems = persons[0]; in the SelectCommand of viewModel,

     public class PersonViewModel: INotifyPropertyChanged
        {
    
            public event PropertyChangedEventHandler PropertyChanged;
    
            protected virtual void OnPropertyChanged(string propertyName)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
    
          //  public Person selectItems { get; set; }
    
            Person _selectItems = new Person();
            public Person selectItems
            {
                get
                {
                    return _selectItems;
                }
    
                set
                {
                    if (_selectItems != value)
                    {
                        _selectItems = value;
                        OnPropertyChanged("selectItems");
    
                    }
                }
    
            }
    
    
            public ObservableCollection<Person> persons { get; set; }
    
            public ICommand FavouriteCommand { protected set; get; }
            public ICommand SelectCommand { protected set; get; }
            public PersonViewModel()
            {
    
                FavouriteCommand = new Command<Person>(async (key) =>
                {
                    Person person = key as Person;
                    selectItems=person;
    
                });
    
                persons = new ObservableCollection<Person>();
                persons.Add(new Person() { Name = "Leon1", Count = 1, Isfavourite = false });
                persons.Add(new Person() { Name = "Leon2", Count = 2, Isfavourite = false });
                persons.Add(new Person() { Name = "Leon3",  Count = 3, Isfavourite = false });
                persons.Add(new Person() { Name = "Leon4",  Count = 4, Isfavourite = false });
                persons.Add(new Person() { Name = "Leon5",  Count = 5, Isfavourite = false });
    
                SelectCommand = new Command(() =>
                {
    
                    selectItems = persons[0];
    
                });
            }
        }
    
  • ycusoyycusoy Member ✭✭
    thanks @LeonLu, this works perfectly.
    but I don't understand is function of ObservableCollection. how to write if we will save to sql database. if you don't mind, try giving an example viewmodel. i want to learn about this.
Sign In or Register to comment.