简体   繁体   English

来自 Linq 的 ObservableCollection

[英]ObservableCollection from Linq

Can someone see what I need to change here?有人可以看到我需要在这里改变什么吗? I am displaying an observablecollection of AddressTypeClass items.我正在显示一个可观察的 AddressTypeClass 项目集合。 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: XAML.CS 文件:

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: XAML 文件:

<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您需要将一个 ItemTemplate 添加到您的列表框,例如

<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.您可以使用我的ObservableComputations库改进您的代码。 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.在您的代码中,每次 MyTableDataContext.AddressTypes dbSet (我假设您正在使用 EntityFramework)更改(新项目或删除)或属性(AddressType.AddressTypeID、AddressType.AddressType)更改时,您都会手动更新 OC。 Using AddressType you can automate that process:使用 AddressType 您可以自动化该过程:

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. theOC 是ObservableCollection并反映了上面代码中提到的 MyTableDataContext.AddressTypes.Local 集合和属性中的所有更改。 Ensure that all properties mentioned in the code above notify of changes through the INotifyProperytChanged interface.确保上面代码中提到的所有属性都通过INotifyProperytChanged接口通知更改。

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

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