|
1 | 1 | # itemtemplate-selector-listview-xamarin |
2 | 2 | ItemTemplateSelector listview xamarin |
| 3 | + |
| 4 | +## Sample |
| 5 | + |
| 6 | +```xaml |
| 7 | +<ContentPage.Resources> |
| 8 | + <ResourceDictionary> |
| 9 | + <local:MyDataTemplateSelector x:Key="MessageTemplateSelector"/> |
| 10 | + </ResourceDictionary> |
| 11 | +</ContentPage.Resources> |
| 12 | +<Grid> |
| 13 | + <sync:SfListView x:Name="ListView" |
| 14 | + ItemTemplate="{StaticResource MessageTemplateSelector}" |
| 15 | + ItemsSource="{Binding Messages}" |
| 16 | + ItemSize="105" |
| 17 | + SelectionMode="None" |
| 18 | + BackgroundColor="#FFFAF0"/> |
| 19 | +</Grid> |
| 20 | + |
| 21 | +Incoming Cell: |
| 22 | +<ViewCell xmlns="http://xamarin.com/schemas/2014/forms" |
| 23 | + xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" |
| 24 | + x:Class="DataTemplateSelector.IncomingViewCell"> |
| 25 | + <code> |
| 26 | + . . . |
| 27 | + . . . |
| 28 | + <code> |
| 29 | +</ViewCell> |
| 30 | + |
| 31 | +Outgoing cell: |
| 32 | +<ViewCell xmlns="http://xamarin.com/schemas/2014/forms" |
| 33 | + xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" |
| 34 | + x:Class="DataTemplateSelector.OutgoingViewCell"> |
| 35 | + <code> |
| 36 | + . . . |
| 37 | + . . . |
| 38 | + <code> |
| 39 | +</ViewCell> |
| 40 | + |
| 41 | +DataTemplateSelector: |
| 42 | + |
| 43 | +class MyDataTemplateSelector : Xamarin.Forms.DataTemplateSelector |
| 44 | +{ |
| 45 | + public DataTemplate IncomingDataTemplate { get; set; } |
| 46 | + public DataTemplate OutgoingDataTemplate { get; set; } |
| 47 | + |
| 48 | + public MyDataTemplateSelector() |
| 49 | + { |
| 50 | + this.incomingDataTemplate = new DataTemplate(typeof(IncomingViewCell)); |
| 51 | + this.outgoingDataTemplate = new DataTemplate(typeof(OutgoingViewCell)); |
| 52 | + } |
| 53 | + |
| 54 | + protected override DataTemplate OnSelectTemplate(object item, BindableObject container) |
| 55 | + { |
| 56 | + var messageVm = item as Message; |
| 57 | + if (messageVm == null) |
| 58 | + return null; |
| 59 | + return messageVm.IsIncoming ? this.incomingDataTemplate : this.outgoingDataTemplate; |
| 60 | + } |
| 61 | + |
| 62 | + private readonly DataTemplate incomingDataTemplate; |
| 63 | + private readonly DataTemplate outgoingDataTemplate; |
| 64 | +} |
| 65 | +``` |
| 66 | + |
| 67 | + |
0 commit comments