WPF多表關聯資料繫結

暖楓無敵發表於2012-01-30
Northwind資料庫的三個表之間依次有一對多關係: 
Customers-Orders-Order Details 

要想在TreeView上表現這種關係,就需要HierarchicalDataTemplate. 

<Grid> 
  <Grid.Resources> 
  <DataTemplate x:Key="detailTemplate"> 
  <Grid> 
  <Grid.ColumnDefinitions> <ColumnDefinition Width="100" /> 
  <ColumnDefinition Width="100" /> 
  <ColumnDefinition Width="100" /> 
  </Grid.ColumnDefinitions> 
  <TextBlock Grid.Column="0" Text="{Binding UnitPrice}" /> 
  <TextBlock Grid.Column="1" Text="{Binding Quantity}" /> 
  <TextBlock Grid.Column="2" Text="{Binding Discount}" /> 
  </Grid> 
  </DataTemplate> 

  <HierarchicalDataTemplate x:Key="orderTemplate" ItemsSource="{Binding Orders2OrderDetails}" ItemTemplate ="{StaticResource detailTemplate}"> 
  <Grid> 
  <Grid.ColumnDefinitions> 
  <ColumnDefinition Width="100"></ColumnDefinition> 
  <ColumnDefinition Width="150"></ColumnDefinition> 
  <ColumnDefinition Width="150"></ColumnDefinition> 
  <ColumnDefinition Width="150"></ColumnDefinition> 
  <ColumnDefinition Width="100"></ColumnDefinition> 
  </Grid.ColumnDefinitions> 
  <TextBlock Grid.Column="0" Text="{Binding Path=OrderID}" /> 
  <TextBlock Grid.Column="1" Text="{Binding Path=OrderDate}" /> 
  <TextBlock Grid.Column="2" Text="{Binding Path=RequiredDate}" /> 
  <TextBlock Grid.Column="3" Text="{Binding Path=ShippedDate}" /> 
  <TextBlock Grid.Column="4" Text="{Binding Path=Freight}" /> 
  </Grid> 
  </HierarchicalDataTemplate> 

  <HierarchicalDataTemplate x:Key="treeTemplate" ItemsSource="{Binding Customers2Orders}" ItemTemplate="{StaticResource orderTemplate}"> 
  <TextBlock Text="{Binding CompanyName}" /> 
  </HierarchicalDataTemplate> 
</Grid.Resources> 

<TreeView Grid.Column="0" Name="myTreeView" ItemsSource="{Binding}" ItemTemplate="{StaticResource treeTemplate}"> 
</TreeView> 
</Grid> 
---------------------------

.cs部分  
 public partial class Window1 : System.Windows.Window 
 { 
 public DataSet ds; 
 public Window1() 
 { 
 InitializeComponent(); 

 ds = new DataSet();  

 SqlConnection conn = new SqlConnection(); 
 conn.ConnectionString = "server=(local);database=northwind;uid=sa;pwd="; 

 SqlCommand cmd = new SqlCommand(); 
 cmd.Connection = conn; 
  
 // Load Customers  
 SqlDataAdapter daCustomers = new SqlDataAdapter("select * from Customers",conn);  
 daCustomers.Fill(ds, "Customers"); 

 // Load Orders 
 SqlDataAdapter daOrders = new SqlDataAdapter("select * from Orders", conn); 
 daOrders.Fill(ds, "Orders"); 


 // Load OrderDetails 
 SqlDataAdapter daOrderDetails = new SqlDataAdapter("select * from [Order Details]", conn); 
 daOrderDetails.Fill(ds, "OrderDetails"); 

  

 ds.Relations.Add("Customers2Orders", ds.Tables["Customers"].Columns["CustomerID"], ds.Tables["Orders"].Columns["CustomerID"]); 
 ds.Relations.Add("Orders2OrderDetails", ds.Tables["Orders"].Columns["OrderID"], ds.Tables["OrderDetails"].Columns["OrderID"]); 

 myTreeView.DataContext = ds.Tables["Customers"]; 

 }   


相關文章