wpfdatagriddatagridtemplatecolumndatagridtextcolumn

WPF DataGridTextColumn and Tag


I have a datagrid with several DataGridTextColumn defined.

I need to use the Textblock's Tag property. I can't find it on a DataGridTextColumn.

I found a workaround which works, i.e a DataTemplateColumn in which I declare the textblock, in which case I have access to the Tag property:

<DataGridTemplateColumn Header="Column with Tag accessible">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Tag="{Binding Variable1Name}"
                       Text="{Binding Variable2Name}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

It would be great however if I could achieve the same result with the DataGridTextColumn. Any idea please?


Solution

  • It would be great however if I could achieve the same result with the DataGridTextColumn.

    You can't since the DataGridTextColumn has no Tag property that you can set.

    It's unclear why you need to set the Tag property at all but if you don't want to create a DataGridTemplateColumn and a CellTemplate for each column, you could create a custom DataGridTextColumn:

    public class CustomDataGridTextColumn : DataGridTextColumn
    { 
        protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) 
        { 
            FrameworkElement fe = base.GenerateElement(cell, dataItem);
            if (fe is TextBlock textBlock)
            { 
                textBlock.SetBinding(TextBlock.TagProperty, new Binding(TagPropertyName));  //use TagProperty here
            }
            return fe;
        }
    
        public string TagPropertyName { get; set; }
    }
    

    Then you simply replace the built-in DataGridTextColumn with this one in your XAML:

    <local:CustomDataGridTextColumn Binding="{Binding Variable2Name}" TagPropertyName="Variable1Name" />