Update SelectedItem template RRS feed

  • Question

  • User388732 posted


    I have a simple CollectionView with an ItemsSource, and I want to change the SelectedItem background when I select a collection element or when I change the bound property in the view model. How can I achieve this?

    Thanks a lot!

    Xamarin Forms version: 4.2

    Tuesday, November 5, 2019 12:35 PM

All replies

  • User372631 posted

    You can use data binding and set the value of SelectedItem in code behind .

    in xaml

    <CollectionView SelectedItem="{Binding SelectItem,Mode=TwoWay}" ItemsSource="{Binding MyItems}" >

    in code behind or ViewModel

    You should firstly implement the interface INotifyPropertyChanged

    ``` public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); }

    private Model selectItem; public Model SelectItem { get { return selectItem; }

    set { if (selectItem != value) { selectItem = value; NotifyPropertyChanged();

         // do something you want when selected item changed

    } ```

    And you can change the value like

    selectItem = MyItems[2];

    Tuesday, November 5, 2019 2:26 PM
  • User388732 posted


    We have already tried this, but we can not see the selection in the UI. The only way we were able to do it was to pre-select it from the constructor, but we want to update it after the view has been rendered.

    Wednesday, November 6, 2019 7:40 AM
  • User372631 posted

    You can set it in method OnAppearing ,if you want to update only first load , you can set a property like bool isFirstLoad .

    Wednesday, November 6, 2019 7:43 AM