简体   繁体   中英

Silverlight DataGrid Header Binding

I am using the HeaderStyle property to customize a Silverlight DataGrid column header. Is there a way to bind controls inside of the ControlTemplate to an object in a collection based on the column index? Something similar to the following?

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

In your header control template:

<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 class:

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];
    }
}

Note that binding to MyCollection will probably not work as expected. You can use a custom attached property to attache the desired collection to the column where it is defined in XAML and then read it here like this (in 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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM