我需要将选定的treeview项(实际上是数据源)绑定到datagrid。
F.ex。我有收据清单,在一张收据下有收据项目清单。当从treeview中选择收据时,我想将这些项绑定到datagrid。
在datagrid中,将对子项进行编辑,因此值应绑定到实际数据源。
怎么做?
答案 0 :(得分:3)
将DataGrids的ItemsSource绑定到树中选定的Receipt:
<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 :(得分: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>
MainWindow背后的代码:
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; }
}
}