Reputation: 520
On a Page, I can use a ControlTemplate
to populate the Page
's Content
.
In this example there are 2 choices for content based on an arbitrary variable, bleDevice
, being null or not...
internal void SetContentViewBindingContext(BleDevice bleDevice)
{
BindingContext = bleDevice;
var controlTemplate = new ControlTemplate(() =>
{
if (bleDevice is null)
return new NoDeviceDataTemplate().LoadTemplate.Invoke();
else
return new BleDeviceDiagnosticItemDataTemplate().LoadTemplate.Invoke();
});
_contentView = new() { ControlTemplate = controlTemplate };
Content = (View)_contentView.ControlTemplate.LoadTemplate();
}
This works fine... And perhaps my understanding of a DataTemplateSelector
is wrong, but I would like to use a DataTemplateSelector
as it seems to me a more elegant way to select the page's content dynamically. But I can't figure out how to do so.
Fwiw, here is what I've tried that doesn't work, for probably obvious reasons I'm not aware:
ControlTemplate ct = new(new DeviceDetailsDataTemplateSelector().LoadTemplate);
_contentView = new() { ControlTemplate = ct };
Content = (View)_contentView.ControlTemplate.LoadTemplate();
Any advice?
Upvotes: 0
Views: 260
Reputation: 7990
A common usage scenario for a DataTemplate
is displaying data from a collection of objects in a ListView, CollectionView or CarouselView. And the DataTemplate is set to the ListView.ItemTemplate
property.
A DataTemplateSelector can be used to choose a DataTemplate at runtime based on the value of a data-bound property. This enables multiple data templates to be applied to the same type of object, to choose their appearance at runtime.
The most common scenarios to use DataTemplateSelector
is for ListView
, CollectionView
or CarouselView
. A DataTemplateSelector is used to choose a DataTemplate at runtime based on the value of a data-bound property. If you see the official sample, you may find the OnSelectTemplate
method in DataTemplateSelector
return a DataTemplate
instead of a ControlTemplate
.
So it may not applicable for this case.
Hope it helps!
Upvotes: 0