使用LinQ从组合框选择中选择C#筛选器列表框

时间:2018-12-07 13:44:39

标签: c# linq xaml combobox listbox

我有一个名为lstTickets的列表框和一个名为cboFilter的组合框。我正在尝试根据票证。组合框中的票证过滤列表框中的项目。因此,例如,如果我从combox中选择,则是列表框中的唯一团队。任何帮助表示赞赏。

 List<Ticket> = new List<Ticket>()
    {
        new Ticket { Name = "Arsenal", Badge = "images/arsenal.jpg", Price = 900, Stadium = "emirates.jpg", District = "London" },
        new Ticket { Name = "Tottenham Hotspur", Badge = "images/tottenham.jpg", Price = 850, Stadium = "tottenham.jpg", District = "" },
        new Ticket { Name = "Manchester United", Badge = "images/.png", Price = 1000, Stadium = "oldtrafford.jpg", District = "" },
    };

 private void cboFilter_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
       var query = from Ticket in tickets where cboFilter.SelectedItem.ToString() == Ticket.District select Ticket;

        lstTickets.ItemsSource = null;
        lstTickets.Items.Clear();

        List<Ticket> tmp = new List<Ticket>();

        foreach (var tickets in query)
        {
            tmp.Add(tickets);

        }
        lstTickets.ItemsSource = tmp;

    }



                        <Image Width="200" Height="150" HorizontalAlignment="Left" Source="{x:Bind Badge }" />
                        <TextBlock FontSize="22" HorizontalAlignment="Left" Text="{x:Bind Name}" Style="{StaticResource HeaderTextBlockStyle}"/>
                        <TextBlock FontSize="16" HorizontalAlignment="Left"> € <Run Text="{Binding Price}" /></TextBlock>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

编辑:在mainpage.cs中填充组合框

private void myGrid_Loaded(object sender, RoutedEventArgs e)
    {
    }

2 个答案:

答案 0 :(得分:0)

看起来ToString()对所选项目无效。

var searchTerm=  cboFilter.SelectedItem.ToString();
var query = from Ticket in tickets where Ticket.District == term  select Ticket;

确保您在搜索字词上设置了一个断点,以查看其获取的正确值

但是我想我知道您的问题,所选项目将返回整个对象,因此执行以下操作

var selectedTicked=  cboFilter.SelectedItem as Ticket;
var searchTerm= selectedTicket.District 
    var query = from Ticket in tickets where Ticket.District == term  select Ticket;

答案 1 :(得分:0)

请尝试首先检查cboFilter.SelectedItem中是否有实际值,然后再使用小写字母比较这些值。我更喜欢使用System.Linq,因此我将您的查询更改为使用它:

private void cboFilter_SelectionChanged(object sender, SelectionChangedEventArgs e)
{

   var comboBoxItem = cboFilter.SelectedItem as ComboBoxItem;

   if(comboBoxItem == null) return; // or log an error here or something if it should not be empty.

   var query = tickets.Where(t => t.District.ToLower() == comboBoxItem.Content.ToString().ToLower());

    lstTickets.ItemsSource = null;
    lstTickets.Items.Clear();

    List<Ticket> tmp = new List<Ticket>();

    foreach (var tickets in query)
    {
        tmp.Add(tickets);

    }
    lstTickets.ItemsSource = tmp;

}