LINQ to SQL as databinding source for WPF Treeview
I wonder if someone could provide a simple example of the following. (preferably in VB.Net):
I have an SQL database with related tables and I am successfully using LINQ to SQL in other areas of my application, but am a little stuck with the Heirarchical Treeview.
I would simply like to use a LINQ query from the database as a source for a WPF Treeview. If I can set the ItemsSource for the treeview as my LINQ result and just set the databinding for treeview items to the various columns that would make my day, but I cant seem to get it cooking.
After spending hours searching the net, I can't find many examples that show this very simply at all. I have found similar ideas but nothing simple and specific for a newbie开发者_JAVA百科 like myself.
As far as I understand, the relationships defined in the DBML file should stay intact when executing the LINQ query. So, can I have something like this as the ItemsSource for the Treeview?
Dim pdc As New ProjectDataContext()
Public Property Selection() As Integer
Dim tree = From c In pdc.Customers _
Where c.CustomerID = _Selection _
Select c
projecttreeview.ItemsSource = tree
Then, the databinding for the TreeView Items could just be {Binding CustomerName) for a parent node and say {Binding Orders.OrderName} as a child node. eg:
<TreeView Name="projecttreeview">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Customers}">
<TextBlock.Text="Binding CustomerName}"/>
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<TextBlock.Text="{Binding Orders.OrderName}"/>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
Obviously this is not quite working out as simply as I would like. Any pointers would be greatly appreciated.
First of all, let me to clarify one issue you probably will run into: when you use query as an ItemsSource
, then the ItemsControl
won't reflect any changes after you will rerun the query, so, assigning the ItemsSource
to a query is very similar to assigning it to the query result converted to an array.
Second, to access related objects/collections (wherever you do it from - would it be a DataTemplate
or simply plain code) you have to explicitly point it out when you creating a query. In Entity Framework you would probably do that by means of Include
method like this: treeview.ItemsSource = tree.Include("Orders")
- it will force the engine to make JOIN
SQL query over the database.
精彩评论