将列表框绑定到ObservableCollection

时间:2012-06-03 23:44:45

标签: wpf class binding observablecollection

我无法找到可以解决此问题的答案。 我有一个ObservableCollection

这是myClass:

public class myClass
    {
      public string name;
      public int[] dimensions = new int[2];
    }

这是设置ObservableCollection:

的代码
public class roomBuilder
{
  private ObservableCollection<myClass> rooms;

      public roomBuilder() //constructor
      {
        string roomName;
        int[] dimensions = new int[2];
        myClass newRoom = new myClass();
        rooms = new ObservableCollection<room>();
        roomName = "Hall";
        dimensions[0] = 10;
        dimensions[1] = 12;
        newRoom.name = roomName;
        newRoom.dimensions = dimensions;
        rooms.Add(newRoom);
        roomListBox.DataContext = rooms;
      }

XAML就是:

    <ListBox Canvas.Left="-1" Canvas.Top="47" Height="419" Name="roomListBox" Width="481"  BorderThickness="1" BorderBrush="GhostWhite" ItemsSource="{Binding}" DataContext="{Binding}"> 

        <ListBox.ItemTemplate  >
            <DataTemplate   >
                <StackPanel Orientation="Vertical" Margin="1" Name="verstack"   > 
                    <StackPanel Orientation="Horizontal" Margin="1" KeyDown="StackPanel_KeyDown" >
                        <TextBox Text="{Binding  Path=name}" IsReadOnly="False" FontFamily="Courier New" FontSize="22" Height="65" VerticalAlignment="Top" TextAlignment="Center"/>
                        <TextBox Name="xDimension" Text="{Binding Mode=TwoWay, Path=dimensions[0] }"  Width="70" Height="65" VerticalAlignment="Top" IsReadOnly="False" FontFamily="Courier New" Margin="2,0,1,0" FontSize="22" MaxLength="3" InputScope="TelephoneNumber" TextAlignment="Center"  />
                    <TextBlock Name="separator" Text=":" FontSize="32"  FontWeight="ExtraBold" Margin="1,4,1,0"  />
                        <TextBox Name="yDimension" Text="{Binding Mode=TwoWay, Path=dimensions[1] }" Width="70" Height="65" VerticalAlignment="Top"   IsReadOnly="False" FontFamily="Courier New" Margin="1,0,2,0" FontSize="22" MaxLength="3" InputScope="TelephoneNumber" TextAlignment="Center"/>

我还没有关闭Xaml,在它下面有一个负载更多,当我运行时没有显示任何内容而我只是不知道问题是什么,我已经敲了2天,请有人帮忙

1 个答案:

答案 0 :(得分:0)

客房必须是您绑定的公共财产。

public ObservableCollection<myClass> rooms
{ 
   get { return ........