我有两个具有Parent Child关系的DataGrids,两者都与数据集合有关。子DataGrid实现DataGridComboBoxColumn以显示父名称而不是id。
问题:How to sort second DataGrid by this column, but by Parent's Name, not by Id?
XAML:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
x:Name="MainWnd"
Title="MainWindow" Height="500" Width="650" Loaded="MainWindow_OnLoaded">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="2*"/>
</Grid.RowDefinitions>
<GridSplitter Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Stretch" Height="5"/>
<local:BaseGrid Grid.Row="0" Margin="3" AutoGenerateColumns="False"
ItemsSource="{Binding ElementName=MainWnd, Path=AColView.View}">
<DataGrid.Columns>
<DataGridTextColumn Header="Id" Binding="{Binding Path=Id}"/>
<DataGridTextColumn Header="Name" Binding="{Binding Path=Aname}"/>
</DataGrid.Columns>
</local:BaseGrid>
<local:BaseGrid Grid.Row="2" Margin="3" AutoGenerateColumns="False"
ItemsSource="{Binding ElementName=MainWnd, Path=BColView.View}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=Id}">
<DataGridTextColumn.Header>
<local:CaptionExtender Caption="Id"/>
</DataGridTextColumn.Header>
</DataGridTextColumn>
<DataGridTextColumn Binding="{Binding Path=Bname}">
<DataGridTextColumn.Header>
<local:CaptionExtender Caption="Name"/>
</DataGridTextColumn.Header>
</DataGridTextColumn>
<DataGridComboBoxColumn x:Name="BparentColumn"
SelectedValueBinding="{Binding ParentId}"
SelectedValuePath="Id"
DisplayMemberPath="Aname">
<DataGridComboBoxColumn.Header>
<local:CaptionExtender Caption="Parent"/>
</DataGridComboBoxColumn.Header>
</DataGridComboBoxColumn>
</DataGrid.Columns>
</local:BaseGrid>
</Grid>
</Window>
代码背后:
public partial class MainWindow
{
private ObservableCollection<A> ACol { get; set; }
private ObservableCollection<B> BCol { get; set; }
public CollectionViewSource AColView { get; private set; }
public CollectionViewSource BColView { get; private set; }
public MainWindow()
{
ACol = new ObservableCollection<A>();
BCol = new ObservableCollection<B>();
AColView = new CollectionViewSource { Source = ACol };
BColView = new CollectionViewSource { Source = BCol };
InitializeComponent();
BparentColumn.ItemsSource = ACol;
}
private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
{
// add parents
for (int i = 1; i <= 5; ++i)
ACol.Add(new A { Id = i, Aname = "Parent " + i.ToString(CultureInfo.InvariantCulture) });
// add children
for (int i = 1; i <= 1000; ++i)
BCol.Add(new B { Id = i, Bname = "Child " + i.ToString(CultureInfo.InvariantCulture), ParentId = (i % ACol.Count) + 1 });
}
}
public class A
{
public int Id { get; set; }
public string Aname { get; set; }
}
public class B
{
public int Id { get; set; }
public int ParentId { get; set; }
public string Bname { get; set; }
}
这就是我想要实现的目标: