开发者

Is it possible to databind directly from a linq query result to a control?

开发者 https://www.devze.com 2023-01-21 01:19 出处:网络
I have just started using WPF and am having trouble data binding from the result of a Linq query to a ListView.

I have just started using WPF and am having trouble data binding from the result of a Linq query to a ListView.

I have tried a number of combinati开发者_如何学运维ons including setting the DataContext and ItemsSource to the query. As in:

listView.DataContext = (from person in People select person).ToList();

Then in the xaml setting the DisplayMemberBinding to {Binding Name} or {Binding /Name} etc.

I'm not worried about any updating either way other than just showing a list of items from the query at this stage.

So I guess i'm missing some pretty basic knowledge with WPF but this part of it seems to have a rather steep learning curve so maybe a nudge in the right direction of some example code would be good. It seems that most code involves a lot of creation of dataviews or notifying datatypes or at least binding to local objects rather than straight from a query.


Try instead:

listView.ItemsSource = (from person in People select person).ToList();

[DataContext sets the binding context for the control and its children. ItemsSource sets the collection used to generate the content of the items in the control.]

You could also simply:

listView.ItemsSource = People;

Fuller example:

MainWindow.xaml:

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListView x:Name="listView">
            <ListView.View>
                <GridView>
                    <GridViewColumn DisplayMemberBinding="{Binding Name}"/>
                    <GridViewColumn DisplayMemberBinding="{Binding Age}"/>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
</Window>

MainWindow.xaml.cs:

using System.Windows;

namespace WpfApplication2
{
  public partial class MainWindow : Window
  {
    public MainWindow()
    {
      InitializeComponent();

      var people = new[] { new { Name = "John", Age = 40 }, new { Name = "Bill", Age = 50 } };
      listView.ItemsSource = people;
    }
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消