Xamarin使用多个datatemplate表单ListView

时间:2014-11-22 08:44:59

标签: listview cell datatemplate xamarin.forms

在XamarinForms中,我必须开发一个显示UserSettings的页面。因此,我创建了一个继承自ContentPage的SettingsPage。在这个页面上,我有一个ListView,其中ItemSource是一个ObservableCollection。 此页面上的所有单元格必须在左侧有一个标签,并在其下方有一个条目。此Cell的右侧必须显示Image或SwitchControl。这取决于它正在显示的UserSetting。

到目前为止,我为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;
        }
}




1 个答案:

答案 0 :(得分:0)

所以实际上我在那里看到两个问题:

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

两者都通过以下方式回答:使用数据绑定!

正如您为Text的{​​{1}}属性Label和[{1}}的属性Text创建了绑定一样,您也可以为属性创建绑定{{1 } Entry。视图模型中属性的类型类型为Source,就像您在Image中为图像的源代码分配了硬编码一样。

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