Silverlight DataGrid标头绑定

时间:2010-10-12 13:41:15

标签: silverlight

我使用HeaderStyle属性来自定义Silverlight DataGrid列标题。有没有办法将ControlTemplate内的控件绑定到基于列索引的集合中的对象?类似于以下内容?

<Style x:Key="GradeDefinitionHeaderStyle" TargetType="dataprimitives:DataGridColumnHeader">
<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate>
            <TextBlock Text="{Binding MyCollection[i]}"/>                        
        </ControlTemplate>
    </Setter.Value>
</Setter>

1 个答案:

答案 0 :(得分:0)

在标头控件模板中:

<Grid>
    <Grid.Resources>
        <local:DataGridColumnBindingHelper x:Key="DataGridColumnBindingHelper"
                                           ElementInColumn="{Binding ., RelativeSource={RelativeSource TemplatedParent}"
                                           Items={Binding MyCollection} />
    </Grid.Resources>
    <TextBlock Text="{Binding CurrentItem, Source={StaticResource DataGridColumnBindingHelper}}"/> 
</Grid>

Inside DataGridColumnBindingHelper类:

private static void OnElementInColumnPropertyChanged(DataGridColumnBindingHelper self, FrameworkElement oldValue, FrameworkElement newValue)
{
    var column = DataGridColumn.GetColumnContainingElement(newValue);
    var dataGrid = newValue.GetVisualAncestors().OfType<DataGrid>().FirstOrDefault(); 
    if (dataGrid != null)
    {
        var columnIndex = dataGrid.Columns.IndexOf(column);
        self.CurrentItem = self.Items[columnIndex];
    }
}

请注意,绑定到MyCollection可能无法按预期工作。 您可以使用自定义附加属性将所需集合附加到在XAML中定义它的列,然后在此处读取它(在DataGridColumnBindingHelper中):

private static void OnElementInColumnPropertyChanged(DataGridColumnBindingHelper self, FrameworkElement oldValue, FrameworkElement newValue)
{
    var column = DataGridColumn.GetColumnContainingElement(newValue);
    var dataGrid = newValue.GetVisualAncestors().OfType<DataGrid>().FirstOrDefault(); 
    if (dataGrid != null)
    {
        var columnIndex = dataGrid.Columns.IndexOf(column);
        var items = DataGridColProperties.GetItems(column); // read attached property
        self.CurrentItem = items[columnIndex]; // you do not need the Items property in this case
    }
}