我有一个我认为是一个非常简单的问题,但由于某种原因,答案正在逃避我。我正在 Silverlight 中创建一个简单的 Master/Detail DataGrid。Web 上的大多数示例通过使用某种集合创建一个对象并将详细信息网格绑定到集合来显示这一点。就我而言,我只想将详细信息网格绑定到与作为主行的行相同的对象。我知道我的示例代码很简单,但我只是想制作最简单的演示来重新创建它。话虽这么说,假设我有这些数据:
public class Customer
{
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public string FavoriteColor { get; set; }
}
public class CustomerCollection : ObservableCollection<Customer>
{
public CustomerCollection()
{
Add(new Customer() { CustomerId = 101, CustomerName = "Todd", FavoriteColor = "Red" });
Add(new Customer() { CustomerId = 102, CustomerName = "Melissa", FavoriteColor = "White" });
Add(new Customer() { CustomerId = 102, CustomerName = "Alicia", FavoriteColor = "Blue" });
Add(new Customer() { CustomerId = 104, CustomerName = "Matthew", FavoriteColor = "Yellow" });
}
}
好的。非常简单。现在,我要将此集合绑定到数据网格。每行都应显示 CustomerId 和 CustomerName。当您单击该行时,我想在详细信息数据网格中显示自己喜欢的颜色。
所以问题是......我如何绑定细节网格,以便它显示最喜欢的颜色?或者换句话说,如何绑定到父行作为我的数据源?
<UserControl x:Class="Sample.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="419" d:DesignWidth="742"
xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
xmlns:src="clr-namespace:Sample">
<UserControl.Resources>
<src:CustomerCollection x:Key="CustDs"></src:CustomerCollection>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White" DataContext="{Binding Source={StaticResource CustDs}}">
<Grid.RowDefinitions>
<RowDefinition Height="56*" />
<RowDefinition Height="363*" />
</Grid.RowDefinitions>
<TextBlock Name="TextBlock1" Text="Customer Information" FontSize="28" TextAlignment="Center" />
<sdk:DataGrid AutoGenerateColumns="False" Grid.Row="1"
Height="301" HorizontalAlignment="Left" Margin="30,22,0,0"
Name="DgCust" VerticalAlignment="Top" Width="681" ItemsSource="{Binding}"
HeadersVisibility="All" ColumnWidth="*">
<sdk:DataGrid.Columns>
<sdk:DataGridTextColumn Header="Customer Id" Binding="{Binding CustomerId}"></sdk:DataGridTextColumn>
<sdk:DataGridTextColumn Header="Customer Name" Binding="{Binding CustomerName}"></sdk:DataGridTextColumn>
</sdk:DataGrid.Columns>
<sdk:DataGrid.RowDetailsTemplate>
<DataTemplate>
<sdk:DataGrid Height="200" Width="600" AutoGenerateColumns="False" ColumnWidth="*"
ItemsSource="{Binding}">
<sdk:DataGrid.Columns>
<sdk:DataGridTextColumn Header="Favorite Color" Binding="{Binding}"></sdk:DataGridTextColumn>
</sdk:DataGrid.Columns>
</sdk:DataGrid>
</DataTemplate>
</sdk:DataGrid.RowDetailsTemplate>
</sdk:DataGrid>
</Grid>
</UserControl>