需要使用 LINQ 将对象绑定到列表框的 WPF 简单示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/495347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:00:10  来源:igfitidea点击:

Need simple example of WPF binding Objects to Listbox with LINQ

wpflinqxamldata-bindinglistbox

提问by Edward Tanguay

The following example successfully binds objects with a ListBoxto display them. However, I would like to create all the objects in one class and then from another class query them with LINQ to fill my XAML ListBox, what would I need to add this example:

以下示例成功将对象与 a 绑定ListBox以显示它们。但是,我想在一个类中创建所有对象,然后从另一个类使用 LINQ 查询它们以填充我的 XAML ListBox,我需要添加这个示例:

XAML:

XAML:

<Window x:Class="WpfApplication15.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300"
        xmlns:local="clr-namespace:WpfApplication15">
    <Window.Resources>
        <ObjectDataProvider x:Key="customers" ObjectType="{x:Type local:Customers}"/>
        <DataTemplate x:Key="LastNameFirst" DataType="WpfApplication15.Customer">
            <StackPanel Margin="10 10 10 0" Orientation="Horizontal">
                <TextBlock Text="{Binding Path=LastName}" FontWeight="bold"/>
                <TextBlock Text=", "/>
                <TextBlock Text="{Binding Path=FirstName}"/>
            </StackPanel>
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <ListBox ItemsSource="{Binding Source={StaticResource customers}}"
                 ItemTemplate="{StaticResource LastNameFirst}"/>
    </Grid>
</Window>

Code behind:

后面的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication15
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }
    }

    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public Customer(string firstName, string lastName)
        {
            this.FirstName = firstName;
            this.LastName = lastName;
        }
    }

    public class Customers : List<Customer>
    {
        public Customers()
        {
            this.Add(new Customer("Jim", "Thompson"));
            this.Add(new Customer("Julie", "Watson"));
            this.Add(new Customer("John", "Walton"));
        }
    }
}

回答by Robert Macnee

edit: added ToList call to the LINQ query

编辑:向 LINQ 查询添加了 ToList 调用

You can just assign the ItemsSource of the ListBox using LINQ in code-behind for this. Assuming you give your ListBox a name:

为此,您可以在代码隐藏中使用 LINQ 分配 ListBox 的 ItemsSource。假设您为 ListBox 命名:

<Window x:Class="WpfApplication15.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:local="clr-namespace:WpfApplication15"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Width="300" Height="300" Title="Window1">
    <Window.Resources>
        <DataTemplate x:Key="LastNameFirst" DataType="WpfApplication15.Customer">
            <StackPanel Margin="10 10 10 0" Orientation="Horizontal">
                <TextBlock FontWeight="bold" Text="{Binding Path=LastName}"/>
                <TextBlock Text=", "/>
                <TextBlock Text="{Binding Path=FirstName}"/>
            </StackPanel>
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <ListBox x:Name="lstCustomers"
                 ItemTemplate="{StaticResource LastNameFirst}"/>
    </Grid>
</Window>

You can assign to ItemsSource in the Loaded event:

您可以在 Loaded 事件中分配给 ItemsSource:

public partial class Window1 : Window 
{
    public Window1()
    {
        this.Loaded += new RoutedEventHandler(Window1_Loaded);
        InitializeComponent(); 
    }

    void Window1_Loaded(object sender, RoutedEventArgs e)
    {
        Customers customers = new Customers();
        lstCustomers.ItemsSource = customers.Where(customer => customer.LastName.StartsWith("W")).ToList();
    }
}

Assuming your LINQ query will change depending on some logic, you can re-assign ItemsSource at the appropriate points.

假设您的 LINQ 查询将根据某些逻辑发生变化,您可以在适当的点重新分配 ItemsSource。

If you want to bind without dipping into code-behind whenever your query logic changes, you're probably better off using a CollectionViewSource, since it has sortingand filteringcapabilities (assuming that's what you're after from using LINQ).

如果您想在查询逻辑发生变化时进行绑定而不陷入代码隐藏,那么最好使用CollectionViewSource,因为它具有排序过滤功能(假设这是您使用 LINQ 的目的)。

回答by Steve Godbold

Take a look @ http://www.codeplex.com/bindablelinqand you should find a bunch of good examples for this.

看看@ http://www.codeplex.com/bindablelinq,你应该会找到一堆很好的例子。