听说WPF支持TreeView的数据绑定,不知哪位做过,能不能举个例子?
听说WPF支持TreeView的数据绑定,不知哪位做过,能不能举个例子?
------解决方案--------------------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);