我有一些自定义datagrid的需求,因此我创建了自己的datagrid扩展WPF datagrid。下面是一些相关的小代码 -
public class ExtendedDataGrid : DataGrid
{
public ExtendedDataGrid()
{
this.SelectionMode = DataGridSelectionMode.Extended;
}
}
我在一个窗口中创建了它的实例,并将
SelectionMode
设置为 Single
,这样做得非常好,属性会被设置为数据网格的 Single
。到目前为止一切都很好。但是如果我将我的 DataGrid 放置在 ControlTemplate 中,
SelectionMode
就永远不会被设置为 Single
。例如,如果我在 DataGrid 的构造函数中显式设置该值,则没有通过 XAML 设置 DP。这里有一个复制问题的小样本 -
<Grid>
<Grid.Resources>
<ControlTemplate x:Key="MyTemplate">
<local:ExtendedDataGrid ItemsSource="{Binding Collection,
RelativeSource={RelativeSource
Mode=FindAncestor,
AncestorType=Window}}"
SelectionMode="Single">
<local:ExtendedDataGrid.Columns>
<DataGridTextColumn Binding="{Binding}"/>
</local:ExtendedDataGrid.Columns>
</local:ExtendedDataGrid>
</ControlTemplate>
</Grid.Resources>
<ContentControl Template="{StaticResource MyTemplate}"/>
<local:ExtendedDataGrid ItemsSource="{Binding Collection,
RelativeSource={RelativeSource
Mode=FindAncestor,
AncestorType=Window}}"
Grid.Row="1" SelectionMode="Single">
<local:ExtendedDataGrid.Columns>
<DataGridTextColumn Binding="{Binding}"/>
</local:ExtendedDataGrid.Columns>
</local:ExtendedDataGrid>
</Grid>
对于第二个DataGrid,它可以正常工作,但对于放置在ControlTemplate内部的DataGrid却无法正常工作。为什么会出现这种奇怪的行为?是DataGrid代码中的某个bug吗?
注意 - 如果我在DataGrid构造函数中注释掉设置SelectionMode为Extended的那一行,它将可以正常工作。我知道这是默认值,并且有很多方法来设置默认值,但我想知道为什么它在一个情况下可以正常工作,在另一个情况下却不行。