Hey,
How can we apply a different Template for the selected item?
Thanks,
Mano
2 Answers, 1 is accepted
The RadListView provides styles; ItemStyle, SelectedItemStyle and PressedItemStyle. See the following documentation for guidance: Item Styles. You can even use a StyleSelector to choose a different style depending on a predefined condition, see ItemStyle Selector documentation.
If you're referring to having a completely different ItemTemplate, almost no ListView type of object provide different DataTemplate-based properties on the condition of selection. You'll instead need to create a Xamarin.Forms.DataTemplateSelector object and assign it to the RadLstView.ItemTemplateSelector property. We have a tutorial on how to accomplish this in the following article: ItemTemplateSelector.
Once you've read that tutorial and are famliar with using a DataTemplateSelector, lets move on to the relevancy to changing a template based on selection.
First, you'll need to sync a model boolean property to your data model if there isn't one yet (make sure you invoke PropertyChanged for this property):
public
class
Student : NotifyPropertyChangedBase
{
public
string
Title {
get
;
set
; }
private
bool
_isItemSelected;
public
bool
IsItemSelected
{
get
=> _isItemSelected;
set
{
if
(_isItemSelected == value)
return
;
_isItemSelected = value;
OnPropertyChanged();
}
}
}
Then, subscribe to the SelectionChanged event of the RadListView and toggle the data item's selected flag accordingly:
private
void
RadListView_SelectionChanged(
object
sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if
(e.OldItems !=
null
)
{
foreach
(var item
in
e.OldItems)
{
(item
as
Student).IsItemSelected =
false
;
}
}
if
(e.NewItems !=
null
)
{
foreach
(var item
in
e.NewItems)
{
(item
as
Student).IsItemSelected =
true
;
}
}
}
Finally, in the template selector, you can use this value to return the appropriate DataTemplate:
public
class
MyItemTemplateSelector : DataTemplateSelector
{
public
DataTemplate RegularTemplate {
get
;
set
; }
public
DataTemplate SelectedTemplate {
get
;
set
; }
protected
override
DataTemplate OnSelectTemplate(
object
item, BindableObject container)
{
if
(item
is
Student student)
{
return
student.IsItemSelected
? SelectedTemplate
: RegularTemplate;
}
return
null
;
}
}
Regards,
Lance | Tech Support Engineer, Sr.
Progress Telerik
Thanks!
It looks like this code is getting what I need:
protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
RadListView listView = container as RadListView;
if (listView == null)
return RegularTemplate;
if (listView.SelectionMode == SelectionMode.Single)
return listView.SelectedItem != null && listView.SelectedItem == item ? SelectedTemplate : RegularTemplate;
else if (listView.SelectionMode == SelectionMode.Multiple)
return listView.SelectedItems.Contains(item) ? SelectedTemplate : RegularTemplate;
else
return RegularTemplate;
}