Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi!

XAML:

HTML
<datagrid>
       ...
       extensions:DataGridExtension.DataContextForColumns="{Binding Mode=OneWay}"
       >


C#:

C#
public class DataGridExtension
{
    static DataGridExtension()
    {
        try
	{
	    //Allows to set DataContextProperty on the columns. Must only be invoked once per application.
	    FrameworkElement.DataContextProperty.AddOwner(typeof (DataGridColumn));
	}
	catch
	{
	}
    }

    public static object GetDataContextForColumns(DependencyObject obj)
    {
        return obj.GetValue(DataContextForColumnsProperty);
    }
	 
    public static void SetDataContextForColumns(DependencyObject obj, object value)
    {
        obj.SetValue(DataContextForColumnsProperty, value);
    }
 
    /// <summary>
    /// Allows to set DataContext property on columns of the DataGrid (DataGridColumn)
    /// </summary>
    /// <example><datagridtextcolumn header="{Binding DataContext.ColumnHeader, RelativeSource= {RelativeSource Self}}" /></example>
    public static readonly DependencyProperty DataContextForColumnsProperty =
                DependencyProperty.RegisterAttached(
	        "DataContextForColumns",
	        typeof(object),
	        typeof(DataGridExtension),
	        new UIPropertyMetadata(OnDataContextChanged));
	 
    /// <summary>
    /// Propogates the context change to all the DataGrid's columns
    /// </summary>
    private static void OnDataContextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var grid = d as DataGrid;
        if (grid == null) return;
	 
        foreach (DataGridColumn col in grid.Columns)
            col.SetValue(FrameworkElement.DataContextProperty, e.NewValue);
    }
}


Resizing by double-clicking on a split line in the header works correct without extensions:DataGridExtension.DataContextForColumns attribute for DataGrid: affects only columns located on the right(it works in such way by default). With this attribute resizing affects columns located on the left. I don't understand this dependency and how to make deal with it. I need both correct resizing and setting the data context for the grid.
Posted
Updated 11-Aug-14 22:57pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900