【问题标题】:ObservableCollection from Linq来自 Linq 的 ObservableCollection
【发布时间】:2012-05-09 00:58:48
【问题描述】:

有人可以在这里看到我需要更改的内容吗?我正在显示 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> 

【问题讨论】:

  • 您的 ItemsSource 在后面的代码中与 .xaml 中的不同。您实际上不需要在后面的代码中设置它,但 .xaml 应该设置为“theOC”。然后将 DisplayMemberPath 设置为 AddressType。

标签: c# linq xaml binding observablecollection


【解决方案1】:

您需要在 ListBox 中添加一个 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>

【讨论】:

    【解决方案2】:

    您可以使用我的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 接口通知更改。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多