【问题标题】:Filter an itemssource of a listbox过滤列表框的项目源
【发布时间】:2013-06-17 10:14:47
【问题描述】:

我正在处理这个例子:http://code.msdn.microsoft.com/wpapps/Beginners-for-how-to-use-45690caa

我在表格中插入了一个新列,称为“类别”

现在我只需要在列表框中查看 category == "card" 的行

这是列表框:

<ListBox x:Name="ContactListBox" Grid.Row="2">
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <Grid>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="100" />
                                        <ColumnDefinition Width="200" />
                                        <ColumnDefinition Width="*" />
                                    </Grid.ColumnDefinitions>
                                    <Image Source="Images\open.png" Margin="-30, -18, 0, 0" Tap="Edit_Tap" Height="75" Width="75"/>
                                    <TextBlock Text="{Binding Name}" Tap="Edit_Tap" Grid.Column="1" FontSize="{StaticResource PhoneFontSizeLarge}" TextAlignment="Left"/>
                                </Grid>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                    </ListBox>

这是列表框的来源:

void Customers_Loaded(object sender, RoutedEventArgs e)
    {
        using (AddressBookDataContext dc = new AddressBookDataContext())
        {

            ContactListBox.ItemsSource = from c in dc.Contacts select c;

        }
    }

我已尝试将其更改为: ContactListBox.ItemsSource = from c in dc.Contacts where c.category == "card" select c; 但我不工作,我该怎么办?

谢谢大家,对不起我的英语不好

【问题讨论】:

    标签: c# linq listbox windows-phone itemssource


    【解决方案1】:

    你没有提到你得到了哪个异常,但听起来你可能得到了`NotSupportedException:成员“[whatever]”没有支持的 SQL 转换错误”。

    如果你搜索这个异常,你会发现很多关于一个共同主题的答案——本质上,Linq2SQL 不知道如何将“类型”翻译成 SQL,所以它会失败。在您的情况下,您可以使用 Linq2SQL 和 Linq2Object 解决此问题:

    // L2S from the DB, transferred to an Enumerable
    var itemSource = (from c in dc.Contacts select c).AsEnumerable();
    
    ContactListBox.ItemsSource = itemSource.Where(c => c.Type == "q");
    
    // or full form Linq
    ContactListBox.ItemsSource = from c in itemSource where c.Type == "q" select c;
    

    在我的情况下,我没有添加列,我只是添加了多个具有不同 Types 的联系人,并仅过滤了 Type "q" 的联系人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-16
      • 2020-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多