添加列表框项目在 xamarin 表单中不起作用

Posted

技术标签:

【中文标题】添加列表框项目在 xamarin 表单中不起作用【英文标题】:Adding listbox items doesn't work in xamarin forms 【发布时间】:2018-07-08 17:55:12 【问题描述】:

在 xamarin 表单开发中,向列表框添加项目效果不佳。

MainPage.xaml

  <ListBox  x:Name="vrlist_panel">
        <ListBox.ItemContainerStyle>
            ....
        </ListBox.ItemContainerStyle>

        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid Margin="0">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="1*"></ColumnDefinition>
                        <ColumnDefinition Width="1*"></ColumnDefinition>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="1*"></RowDefinition>
                    </Grid.RowDefinitions>

                    <Border Grid.Column="0" Grid.Row="0">
                        <Image Source="Binding leftImg" Height="100" Margin="14,2,13,20"></Image>
                    </Border>
                    <Border Grid.Column="1" Grid.Row="0">
                        <Image Source="Binding rightImg" Height="100" Margin="14,2,13,20"></Image>
                    </Border>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>

  </ListBox>

MainPage.xaml.cs

public class VRDataModel

    public string leftImg  get; set; 

    public string rightImg  get; set; 



public partitial class MainPage : Page , 
                                    Autodesk.Revit.UI.IDockablePaneProvider

         ....
     private static ObservableCollection<VRDataModel> vrImgs = new 
                                       ObservableCollection<VRDataModel>();
         ....



    ...
vrlist_panel.ItemsSource = vrImgs;
    ...

这是完整的代码。 但是即使 vrImgs 是有效值,vrlist_panel.ItemsSource 的值在运行时也是null,它会导致异常。 几天来我一直在尝试解决此问题,但找不到原因。 我该怎么办?

【问题讨论】:

这似乎不是 XF - 它不支持 ListBox。 真的吗?那为什么编译时不会出现错误?如果它不支持 listbox ,则编译必须失败。你能解释一下吗? 我怀疑您正在构建的并不是真正的 XF 应用程序 - 它似乎是 WPF 或 UWP 在我看来,XF 是一个平台,而 WPF 是一个 GUI 框架。所以我认为我们使用 WPF 在 XF 中进行设计。实际上我在 xamarin 方面没有太多经验,所以你能解释一下 WPF 和 XF 吗?比如差异。 WPF 不会在 iosandroid 上运行,XF 会。 XF 已经有据可查 - developer.xamarin.com/guides/xamarin-forms 【参考方案1】:

您的示例不完整,但如果您在尝试设置 ItemsSource 属性时得到 NullReferenceException,则您可能没有在设置属性之前调用 InitializeComponent() 方法:

public partial class MainPage : Page

    public MainPage()
    
        InitializeComponent();
        ...
        vrlist_panel.ItemsSource = vrImgs;
    

【讨论】:

以上是关于添加列表框项目在 xamarin 表单中不起作用的主要内容,如果未能解决你的问题,请参考以下文章

ListView.HasUnevenRows 属性在 Xamarin.Forms.iOS 中不起作用

绑定到 ViewModel 在 Xamarin.Forms 中不起作用

OnOptionsItemSelected 在 Xamarin 中不起作用

ListView 项目在 Xamarin 表单中不展开折叠高度

表单权限在具有多个表单的模块中不起作用

Xamarin.CommunityToolKit TouchEffect.Command 在 UWP 中不起作用