Hi
How can I change TextCell binding in runtime
<Switch IsToggled="false" Toggled="Switch_Toggled" /> <ListView x:Name="listview" > <ListView.ItemTemplate> <DataTemplate> <TextCell x:Name="textcell" Text="{Binding productName}"/> </DataTemplate> </ListView.ItemTemplate> </ListView>
You can achieve it by DataTemplateSelector
, for example, I create a two DataTemplate
like following code.
<ContentPage.Resources> <ResourceDictionary> <DataTemplate x:Key="NormalTweetTemplate"> <TextCell Text="{Binding Name}"></TextCell> </DataTemplate> <DataTemplate x:Key="PromotedTweetTemplate"> <TextCell Text="{Binding Age}"></TextCell> </DataTemplate> <local:MyTemplateSelector x:Key="TweetTemplateSelector" NormalTweetTemplate="{StaticResource NormalTweetTemplate}" PromotedTweetTemplate="{StaticResource PromotedTweetTemplate}" /> </ResourceDictionary> </ContentPage.Resources>
if I changed have a property called IsSwitch
If it value of IsSwitch
is false, set PromotedTweetTemplate
, If it value of IsSwitch
is true, set NormalTweetTemplate
. Create a DataTemplateSelector
to acheve it.
public class MyTemplateSelector : DataTemplateSelector { public DataTemplate NormalTweetTemplate { get; set; } public DataTemplate PromotedTweetTemplate { get; set; } protected override DataTemplate OnSelectTemplate(object item, BindableObject container) { if (((MyModel)item).IsSwitch is true) return NormalTweetTemplate; if (((MyModel)item).IsSwitch is false) return PromotedTweetTemplate; return NormalTweetTemplate; } } }
Listview used it DataTemplateSelector
like following code.
<ListView ItemsSource="{Binding MyModels}" ItemTemplate="{StaticResource TweetTemplateSelector}" />
MyModel have tree property like following code.
public class MyModel:INotifyPropertyChanged { public string Name { get; set; } public string Age { get; set; } public bool IsSwitch { get; set; } }
If the IsSwitch is true , TextCell binding Name, IsSwitch is false, TextCell binding Age like following screenshot.
Here is helpful article about it.
Answers
You can achieve it by
DataTemplateSelector
, for example, I create a twoDataTemplate
like following code.if I changed have a property called
IsSwitch
If it value ofIsSwitch
is false, setPromotedTweetTemplate
, If it value ofIsSwitch
is true, setNormalTweetTemplate
. Create aDataTemplateSelector
to acheve it.Listview used it
DataTemplateSelector
like following code.MyModel have tree property like following code.
If the IsSwitch is true , TextCell binding Name, IsSwitch is false, TextCell binding Age like following screenshot.
Here is helpful article about it.
https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/templates/data-templates/selector
Thank you very much for the answer