我在RowDataTemplete中使用DataGrid创建了一个DataGrid。我需要以下列方式绑定它
<DataGrid Name="dgUsers" AutoGenerateColumns="False" Background="#FFDED6D6">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}" IsReadOnly="True" Foreground="#FF9C2626" />
<DataGridTextColumn Header="Birthday" Binding="{Binding Birthday}" IsReadOnly="True" />
</DataGrid.Columns>
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<DockPanel Background="GhostWhite">
<Image DockPanel.Dock="Left" Source="{Binding ImageUrl}" Height="64" Margin="10" />
<Grid Margin="0,10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Item" Binding="{Binding Path=Items.item}" IsReadOnly="True" Foreground="#FF9C2626" />
<DataGridTextColumn Header="Qty" Binding="{Binding Path=Items.qty}" IsReadOnly="True" />
</DataGrid.Columns>
</DataGrid>
</Grid>
</DockPanel>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
</DataGrid>
cs代码如下所示
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<User> users = new List<User>();
users.Add(new User() { Id = 1, Name = "John Doe", Birthday = new DateTime(1971, 7, 23), ImageUrl = "http://www.wpf-tutorial.com/images/misc/john_doe.jpg", Items = new Items() { item="Thenga",qty="2"} });
users.Add(new User() { Id = 2, Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17), Items = new Items() { item="Olakka",qty="5"} });
users.Add(new User() { Id = 3, Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2), Items = new Items() { item = "Punnaak", qty = "3" } });
dgUsers.ItemsSource = users;
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime Birthday { get; set; }
public string ImageUrl { get; set; }
public Items Items { get; set; }
}
public class Items
{
public string item { get; set; }
public string qty { get; set; }
}
}
运行上面的代码后; RowDetailsTemplate没有绑定我的数据。我需要你帮助将DataGrid绑定到DataGrid作为RowDetailsTemplate
答案 0 :(得分:1)
如果我了解您的问题,您希望将内部DataGrid
绑定到Items
属性。如果是这种情况,那么第一个问题是你需要将ItemsSource
绑定到Items
属性而不是整个User
,然后将内部DataGrid
的列绑定到{{1的属性}}
Items
第二个问题是<DataGrid.RowDetailsTemplate>
<DataTemplate>
<!-- .... -->
<DataGrid ItemsSource="{Binding Items}" ...>
<DataGrid.Columns>
<DataGridTextColumn Header="Item" Binding="{Binding Path=item}" IsReadOnly="True" Foreground="#FF9C2626" />
<DataGridTextColumn Header="Qty" Binding="{Binding Path=qty}" IsReadOnly="True" />
</DataGrid.Columns>
</DataGrid>
<!-- .... -->
</DataTemplate>
</DataGrid.RowDetailsTemplate>
是单个项目,而不是列表。如果要将某些内容绑定到Users
属性,则它必须是ItemsSource
,因此在您的视图模型中将其转换为列表
IEnumerable