2014-11-22 44 views
0

在XamarinForms我必须开发一个显示UserSettings的页面。因此我创建了一个从ContentPage继承的SettingsPage。在这个页面上,我有一个ListView哪个ItemSource是一个ObservableCollection。 此页面上的所有单元格必须在其左侧有一个标签,并在其下面有一个条目。该单元的右侧必须显示一个图像或SwitchControl。这取决于它显示的UserSetting。Xamarin Forms ListView与多个数据模板

到目前为止,我为ListView的ItemTemplate创建了一个SettingsPage和一个自定义Cell。在这个代码中,所需的图像是硬编码的,在将来也必须改变。 达成此目的的最佳方法是什么?我对XamarinForms完全陌生,因此对代码的提示非常感谢。

感谢, HJS

public class SettingsPage : ContentPage 
 
{ 
 
     public SettingsPage() 
 
     { 
 
       var userSettings = DemoData.UserSettings(); 
 
       var listView = new ListView { ItemsSource = userSettings }; 
 
       listView.ItemTemplate = new DataTemplate (typeof(UserCell)); 
 
       listView.RowHeight = 60; 
 

 
       Content = listView; 
 
     } 
 
}

public class UserCell : ViewCell 
 
{ 
 
     public UserCell() 
 
     { 
 
       var titleLabel = new Label(); 
 
       var titleBinding = new Binding ("Name"); 
 
       titleLabel.SetBinding (Label.TextProperty, titleBinding); 
 

 
       var valueEntry = new Entry(); 
 
       var valueBinding = new Binding ("Value"); 
 
       valueEntry.SetBinding (Entry.TextProperty, valueBinding); 
 

 
       var accessoryImage = new Image(); 
 
       accessoryImage.Source = "ic_action_new.png"; 
 

 
       var stackLayout = new StackLayout(); 
 
       stackLayout.Children.Add (titleLabel); 
 
       stackLayout.Children.Add (valueEntry); 
 

 
       var grid = new Grid { 
 

 
         HorizontalOptions = LayoutOptions.StartAndExpand, 
 
         VerticalOptions = LayoutOptions.FillAndExpand, 
 

 
         ColumnDefinitions = { 
 
           new ColumnDefinition{ Width = 200 }, 
 
           new ColumnDefinition{ Width = 50 } 
 
         } 
 
       }; 
 

 
       grid.Children.Add (stackLayout, 0, 0); 
 
       Grid.SetColumnSpan (stackLayout, 1); 
 
       grid.Children.Add (accessoryImage, 1, 0); 
 

 
       View = grid; 
 
     } 
 
}

回答

0

所以其实我看到有两个问题:

  • 如何更改硬编码图片
  • 如何显示无论是SwitchControlImage

两者都是由回答:使用数据绑定!

正如你已经创建了财产Label的财产EntryText你还可以创建属性的ImageSource绑定Text绑定。您的视图模型中的媒体资源类型将为string,就像您为ViewCell中的硬件编码分配了一个字符串。

而且要么显示SwitchControlImage,你也可以绑定属性IsVisible这两个ImageVisualElementSwitchControl继承。所以你基本上实例化一个Image和一个SwitchControl并将它们添加到你的布局ViewCell并将它们各自的IsVisible属性绑定到你的视图模型的两个不同的布尔属性。这允许您实现逻辑来决定何时在您的视图模型中显示一个或另一个视图模型,就像它应该在MVVM中一样。

+0

感谢您的回复。借助互联网的一些帮助,我为ListView编写了一个DataTemplateSelector。但我会尝试一下你的建议。 – HJS 2014-11-26 11:47:07