0

谁能告诉我如何将数据绑定到列表框。

          listbox_mypet.ItemsSource = pg_addPet.list_listMyPet;

我的课是

    public class SaveMypet
  {
    public string Name { get; set; }
    public string Birthday { get; set; }
    public string FavFood { get; set; }
    public string DocNo { get; set; }
    public string VacDate { get; set; }
    public string FavToy { get; set; }
   // public ImageSource  Image1 { get; set; }

}

我的代码不起作用

          <ListBox Foreground="Black" FontSize="24" Canvas.Left="20" Canvas.Top="80" Height="313" Name="listbox_mypet" Width="415" Margin="20,80,-435,-393">

                        <ListBox.ItemTemplate>
                                <DataTemplate>
                                    <StackPanel Orientation="Horizontal">
                                        <TextBlock Text="{Binding Name}"> </TextBlock>
                                        <TextBlock Text="{Binding Birthday}"> </TextBlock>
                                    <TextBlock Text="{Binding FavFood}"> </TextBlock>
                                    <TextBlock Text="{Binding DocNo}"> </TextBlock>
                                    <TextBlock Text="{Binding VacDate}"> </TextBlock>
                                    <TextBlock Text="{Binding FavToy}"> </TextBlock>
                                </StackPanel>
                                </DataTemplate>
                            </ListBox.ItemTemplate>
                        </ListBox>

它显示 System.Windows.Controls.TextBox

4

2 回答 2

0

在您的 page.xaml.cs 中执行此操作 ..

 public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
        lstSaveMypet = new ObservableCollection<SaveMypet>();
        SaveMypet objsaveMypet = new SaveMypet();
        objsaveMypet.Birthday = "birthday1";
        objsaveMypet.DocNo = "asdklfj";
        objsaveMypet.FavFood = "pizza";
        objsaveMypet.Name = "tom";
        objsaveMypet.VacDate = "asfhak";
        objsaveMypet.FavToy = "ajdfhk";

        lstSaveMypet.Add(objsaveMypet);
        lstSaveMypet.Add(objsaveMypet);
        lstSaveMypet.Add(objsaveMypet);
        lstSaveMypet.Add(objsaveMypet);
        lstSaveMypet.Add(objsaveMypet);

        listbox_mypet.ItemsSource = lstSaveMypet;
        this.DataContext = this;


    }

    private ObservableCollection<SaveMypet> _lstSaveMypet;
    public ObservableCollection<SaveMypet> lstSaveMypet
    {
        get
        {
            return _lstSaveMypet;
        }
        set
        {
            _lstSaveMypet = value;

        }
    }

在这里我使用了虚拟数据。

于 2013-07-04T11:45:04.830 回答
0

到目前为止,您所做的非常出色。但我认为您在将数据添加到列表时可能出错了。这是我的建议。

List<SaveMyPet> source=new List<SaveMyPet>();
source.Add(new SaveMyPet(Name="Dumpy", Birthday="21/3/2012", FavFood="Bone:,DocNo="23",VacDate="21/3/2013",FavToy="Bone"));

listbox_mypet.DataContext=this;
listbox_mypet.ItemSource=source;

您可以将尽可能多的 SaveMyPet 项目添加到列表中,并最终将其添加到源中。ObservableCollection 也可以正常工作。对此有疑问,请评论!

于 2013-07-04T12:21:05.743 回答