This project is read-only.

Changing Datacontext for Header in DataGrid

Oct 9, 2014 at 8:46 PM
Hi

I have been using the DataGrid control and I need to have the possibility to databind the header of DataGridTextColumn to a property of my view model.
<StackPanel  
    x:Name="RootElement"
    DataContext="{Binding MyViewModel}">
    <MtkControls:DataGrid 
        Style="{StaticResource StandardDataGridStyle}"
        ItemsSource="{Binding Lines}"
        SelectedItem="{Binding SelectedLine, Mode=TwoWay}"
        HeaderTemplate="{StaticResource ListColumnHeaderTemplate}">
        <MtkControls:DataGrid.Columns>
            <MtkControls:DataGridTextColumn 
<!--I am unable to change the DataContext to MyViewModel in the next line-->
                Header="{Binding DataContext.Label, ElementName=RootElement}" 
                Binding="{Binding ItemId}"/>
        </MtkControls:DataGrid.Columns>
    </MtkControls:DataGrid>
</StackPanel>
Has anyone had this issue and managed to fix it?
Oct 9, 2014 at 9:10 PM
If you instantiate the view model as resource (see https://mytoolkit.codeplex.com/wikipage?title=ViewModelBase&referringTitle=Documentation) then you can reference it like this:
Header="{Binding Label, Source={StaticResource ViewModel}}"
otherwise this should work
 <StackPanel>
    <StackPanel.Resources>
        <FrameworkElement Tag="{Binding MyViewModel}" x:Key="Proxy" />
    </StackPanel.Resources>
    
    <MtkControls:DataGrid 
        Style="{StaticResource StandardDataGridStyle}"
        ItemsSource="{Binding Lines}"
        SelectedItem="{Binding SelectedLine, Mode=TwoWay}"
        HeaderTemplate="{StaticResource ListColumnHeaderTemplate}">
        <MtkControls:DataGrid.Columns>
            <MtkControls:DataGridTextColumn 
                Header="{Binding Tag.Label, Source={StaticResource Proxy}}" 
                Binding="{Binding ItemId}"/>
        </MtkControls:DataGrid.Columns>
    </MtkControls:DataGrid>
</StackPanel>
Marked as answer by palmar on 10/9/2014 at 1:56 PM
Oct 9, 2014 at 9:55 PM
This worked exactly as intended, thank you for a very quick response.
Oct 9, 2014 at 10:30 PM
You're welcome. If you like the library please tell others about it, follow and review it :)