正如標題所說,我嘗試在DataGrid中獲取DataGrid。用我的代碼,什麼都沒有,那麼列名顯示出來。在某些時候,我可以顯示來自第一個DataGrid的數據,但現在沒有什麼。WPF在DataGrid中的Visual C#DataGrid
XAML:
<Window x:Class="WpfDataGridSample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="200" Width="400">
<Grid Margin="10">
<DataGrid Name="dgUsers" AutoGenerateColumns="False" ItemsSource="{Binding User}">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}" />
<DataGridTextColumn Header="Birthday" Binding="{Binding Birthday}" />
</DataGrid.Columns>
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<DataGrid Name="dgUserAddress" AutoGenerateColumns="False" ItemsSource="{Binding Address}">
<DataGrid.Columns>
<DataGridTextColumn Header="Street" Binding="{Binding Street}" />
<DataGridTextColumn Header="Number" Binding="{Binding Number}" />
</DataGrid.Columns>
</DataGrid>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
</DataGrid>
</Grid>
</Window>
XAML.CS:
namespace WpfDataGridSample
{
public partial class MainWindow: Window
{
public MainWindow()
{
InitializeComponent();
List<User> User = new List<User>();
var user1 = new User()
{
Id = 1,
Name = "John Doe",
Birthday = new DateTime(1971,7,23)
};
user1.Address.Add(new Address()
{
Street = "Teststreet1",
Number = 1
});
user1.Address.Add(new Address()
{
Street = "Teststreet1",
Number = 11
});
User.Add(user1);
var user2 = new User()
{
Id = 2,
Name = "Jane Doe",
Birthday = new DateTime(1974,1,17)
};
user2.Address.Add(new Address()
{
Street = "Teststreet2",
Number = 2
});
user2.Address.Add(new Address()
{
Street = "Teststreet2",
Number = 22
});
User.Add(user2);
var user3 = new User()
{
Id = 3,
Name = "Sammy Doe",
Birthday = new DateTime(1991,9,2)
};
user3.Address.Add(new Address()
{
Street = "Teststreet3",
Number = 3
});
user3.Address.Add(new Address()
{
Street = "Teststreet3",
Number = 33
});
User.Add(user3);
}
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime Birthday { get; set; }
public List<Address> Address { get; set; }
public User()
{
Address = new List<Address>();
}
}
public class Address
{
public string Street { get; set; }
public int Number { get; set; }
}
}
正如我試過它,它只拋出錯誤,甚至無法編譯它:/ –
你可以發佈錯誤,請問? – Michelle
那麼有115個錯誤:S 'InitializeComponent(); public List User {get;組; } VAR USER1 =新用戶(){ ID = 1, NAME = 「李四」, 生日=新的日期時間(1971,7,23) };'ümeaned這樣嗎? –