2012-02-02 54 views
1

我需要將選定的treeview項(實際上是其數據源)綁定到datagrid。如何通過DataSource將TreeView的SelectedItem綁定到Datagrid

F.ex.我有收據清單,在一張收據下有收據項目清單。我想從treeview中選擇收據時將這些項綁定到datagrid。

在datagrid收據項目將被編輯,所以值應綁定到實際的數據源。

如何做到這一點?

回答

3

綁定您的DataGrid中的ItemsSource在樹中選擇的收據:

<TreeView x:Name="ReceiptsTree" ItemsSource="{Binding Receipts}"/> 


    <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding ElementName=ReceiptsTree, Path=SelectedItem.ReceiptItems}"> 
    <DataGrid.Columns> 
     <DataGridTextColumn Header="Receipt Name" Binding="{Binding Name}" /> 
     .... 
    </DataGrid.Columns> 
    </DataGrid> 
1

這個例子,所有這一切在本質上裸露(在根據DataGrid中的一個SvenG的幫助不大)。

Window.xaml:

<Window x:Class="WpfSOTreeviewSelectedItem.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> 
     <Grid.ColumnDefinitions> 
      <ColumnDefinition Width="*"/> 
      <ColumnDefinition Width="*"/> 
     </Grid.ColumnDefinitions> 
     <TreeView Name="tvReceipts" Grid.Column="0"> 
      <TreeView.ItemTemplate> 
       <DataTemplate> 
        <TextBlock Text="{Binding Path=Name}"></TextBlock> 
       </DataTemplate> 
      </TreeView.ItemTemplate> 
     </TreeView> 
     <DataGrid AutoGenerateColumns="False" Grid.Column="1" ItemsSource="{Binding ElementName=tvReceipts, Path=SelectedItem.Items}"> 
      <DataGrid.Columns> 
       <DataGridTextColumn Header="Ingredient" Binding="{Binding Name}" /> 
      </DataGrid.Columns> 
     </DataGrid> 
    </Grid> 
</Window> 

碼主窗口的背後:

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

     List<Receipt> list = new List<Receipt>(); 

     Receipt r; 
     r = new Receipt() { Name = "Pizza" }; 
     list.Add(r); 

     ReceiptItem ri; 
     ri = new ReceiptItem() { Name = "Tomatoes" }; 
     r.Items.Add(ri); 
     ri = new ReceiptItem() { Name = "Herbs" }; 
     r.Items.Add(ri); 

     r = new Receipt() { Name = "Tortellini" }; 
     list.Add(r); 
     ri = new ReceiptItem() { Name = "Flower" }; 
     r.Items.Add(ri); 
     ri = new ReceiptItem() { Name = "Meat" }; 
     r.Items.Add(ri); 

     r = new Receipt() { Name = "Tarte Tatin" }; 
     list.Add(r); 
     ri = new ReceiptItem() { Name = "Apples" }; 
     r.Items.Add(ri); 
     ri = new ReceiptItem() { Name = "Raisins" }; 
     r.Items.Add(ri); 

     tvReceipts.ItemsSource = list; 
    } 
} 

public class Receipt 
{ 
    private String _name; 
    public String Name 
    { 
     get { return _name; } 
     set { _name = value; } 
    } 

    private List<ReceiptItem> _items = new List<ReceiptItem>(); 
    public List<ReceiptItem> Items 
    { 
     get { return _items; } 
     set { _items = value; } 
    } 
} 

public class ReceiptItem 
{ 
    private String _name; 
    public String Name 
    { 
     get { return _name; } 
     set { _name = value; } 
    } 
} 
相關問題