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