Binding data to Header for LongListSelector (toolkit)
-
19-02-2021 - |
Question
I would like to bind data to the a LongListSelector's header template. Here is the xaml code
<toolkit:LongListSelector x:Name="_List" Background="Transparent" IsFlatList="True" ItemTemplate="{StaticResource SmallImageTemplate}"
ListHeaderTemplate="{StaticResource ListHeader}" ListFooterTemplate="{StaticResource EmptyListFooter}" />
and in c# i have :
_List.ItemsSource = ListOfItems;
but i would like to have a different header for every scenario, so how can i bind data to the template header?
Solution
Use a DataTemplateSelector , and determine what template you want to use, based on the bound data.
You can also use this for the question you asked the other day.
public class DataTemplateSelector : ContentControl
{
public virtual DataTemplate SelectTemplate(object item, DependencyObject container)
{
throw new NotImplementedException();
}
protected override void OnContentChanged(object oldContent, object newContent)
{
base.OnContentChanged(oldContent, newContent);
ContentTemplate = SelectTemplate(newContent, this);
}
}
and then a template of your choice, depending on data. Here's one of mine:
public class EventTemplateSelector : DataTemplateSelector
{
public DataTemplate BreakTemplate
{
get;
set;
}
public DataTemplate EventTemplate
{
get;
set;
}
public DataTemplate DefaultTemplate
{
get;
set;
}
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
if (item == null)
return DefaultTemplate;
// important stuff here
var _event = item as ConferenceEvent;
if (_event != null)
return _event.IsBreak ? BreakTemplate : EventTemplate;
else
return DefaultTemplate;
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow