Linq中的ObservableCollection

问题描述 投票:0回答:2

有人可以在这里看到我需要更改的内容吗?我正在显示AddressTypeClass项目的observablecollection。对象项目而不是数据显示在列表框中。我可以在调试模式下查看对象中的数据。

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;

XAML文件:

<ListBox Name="listBox1" Margin="8" Height ="200" Width ="150" FontSize="12" Foreground="#FF2F3806"  ItemsSource="{Binding AddressType}" IsSynchronizedWithCurrentItem="True" >
    </ListBox> 
c# linq xaml binding observablecollection
2个回答
0
投票

例如,您需要将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>

0
投票

您可以使用ObservableComputations改善代码。在您的代码中,每次MyTableDataContext.AddressTypes dbSet(我假设您正在使用EntityFramework)更改(新项或删除)或属性AddressType.AddressTypeID或AddressType.AddressType更改时,都手动更新OC。使用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是ObservableCollection,并反映了上面代码中提到的MyTableDataContext.AddressTypes.Local集合和属性中的所有更改。确保上面代码中提到的所有属性都通过INotifyProperytChanged界面通知更改。

© www.soinside.com 2019 - 2024. All rights reserved.