简体   繁体   中英

ObservableCollection from Linq

Can someone see what I need to change here? I am displaying an observablecollection of AddressTypeClass items. The object items show up in the listbox instead of the data. I can see the data in the objects in debug mode.

THE XAML.CS FILE:

DataContext MyTableDataContext = new MyTableDataContext();
ObservableCollection<AddressTypeClass> theOC = new ObservableCollection<AddressTypeClass>(new MyTableDataContext().AddressTypes.AsEnumerable()
        .Select(lt => new AddressTypeClass
        {
          AddressTypeID = lt.AddressTypeID,
          AddressType = lt.AddressType,
        })
          .ToList());
this.listBox1.ItemsSource = theOC;

THE XAML FILE:

<ListBox Name="listBox1" Margin="8" Height ="200" Width ="150" FontSize="12" Foreground="#FF2F3806"  ItemsSource="{Binding AddressType}" IsSynchronizedWithCurrentItem="True" >
    </ListBox> 

You need to add an ItemTemplate to your ListBox, eg

<ListBox Name="listBox1" Margin="8" Height ="200" Width ="150" FontSize="12" Foreground="#FF2F3806"  ItemsSource="{Binding AddressType}" IsSynchronizedWithCurrentItem="True" >
   <ListBox.ItemTemplate>
    <DataTemplate>
      <StackPanel>
        <TextBlock Text="{Binding Path=AddressType}" />
      </StackPanel>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

You can impove your code by using my ObservableComputations library. In your code you manualy update theOC every time MyTableDataContext.AddressTypes dbSet (I assume you are using EntityFramework) changes (new item or remove) or properties (AddressType.AddressTypeID, AddressType.AddressType) changes. Using AddressType you can automate that process:

DataContext MyTableDataContext = new MyTableDataContext();
ObservableCollection<AddressTypeClass> theOC = MyTableDataContext.AddressTypes.Local
        .Selecting(lt => new AddressTypeClass
        {
          AddressTypeID = lt.AddressTypeID,
          AddressType = lt.AddressType,
        });
this.listBox1.ItemsSource = theOC;

theOC is ObservableCollection and reflects all the changes in the MyTableDataContext.AddressTypes.Local collection and properties mentioned in the code above. Ensure that all properties mentioned in the code above notify of changes through the INotifyProperytChanged interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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