开发者

Silverlight DataGrid Header Binding

I am using the HeaderStyle property to customize a Silverlight DataGrid column header. I开发者_高级运维s 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
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜