简体   繁体   English

wp7的ListBox绑定数据错误

[英]wp7 Error in Binding Data of ListBox

I am trying to use a collection of checkboxes (created in runtime) within a ListBox. 我正在尝试在ListBox中使用复选框的集合(在运行时创建)。 The XAML I am writing is 我正在编写的XAML是

<ListBox DataContext="{Binding}" Name="cuisineList">
               <ListBox.ItemTemplate>
                    <DataTemplate>

                        <Grid Height="45" Name="grid1" Margin="0,0,0,0">
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="230*" />
                                    <ColumnDefinition Width="230*" />
                                </Grid.ColumnDefinitions>
                            <CheckBox Content="{Binding content}" Name="{Binding name}" Grid.Column="0"/>
                            <CheckBox Content="{Binding content}" Name="{Binding name}" Grid.Column="1"/>
                        </Grid>

                    </DataTemplate>
        </ListBox.ItemTemplate>
</ListBox>

and the code is 和代码是

public ObservableCollection<Cuisine> Items = new ObservableCollection<Cuisine>();
    public Search()
    {
        InitializeComponent();
        for (int i = 0; i < 100; i++)
        {
            Items.Add(new Cuisine());
        }
        cuisineList.DataContext = Items;
    }

But when I run my app, I don't see any check box. 但是,当我运行我的应用程序时,我没有看到任何复选框。 Please point out the mistake and help me rectify it. 请指出错误并帮助我纠正。 Thanks in advance! 提前致谢!

You need to set the itemsource of the listbox as follows 您需要如下设置列表框的itemsource

<ListBox ItemsSource="{Binding Items}" Name="cuisineList">

                    <Grid Height="45" Name="grid1" Margin="0,0,0,0">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="230*" />
                                <ColumnDefinition Width="230*" />
                            </Grid.ColumnDefinitions>
                        <CheckBox Content="{Binding content}" Name="Check1" Grid.Column="0"/>
                        <CheckBox Content="{Binding content}" Name="Check2" Grid.Column="1"/>
                    </Grid>

                </DataTemplate>
    </ListBox.ItemTemplate>

Also is there any restriction to write Items in *.xaml.cs file ?? 在* .xaml.cs文件中写入项目也没有任何限制?

If not write in a view model say PageViewModel.cs file 如果未在视图模型中写入,请说PageViewModel.cs文件

then Set Viewmodel class object as page.xaml data context. 然后将Viewmodel类对象设置为page.xaml数据上下文。 (

this.DataContext = new PageViewModel(); this.DataContext = new PageViewModel();

Write the this statement in the constructor of Page.xaml.cs file) 在Page.xaml.cs文件的构造函数中写入this语句)

Also verify that the Cuisine has public property Content 还要确认美食具有公共财产内容

您需要在列表框上设置项目来源。

<ListBox ItemsSource="{Binding}" Name="cuisineList">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM