Search code examples
c#wpfbindingwpfdatagriddatacontext

How can I make a constant string available to my code and a DataGrid?


I have a Window with a DataGrid in it. My DataGrid handles the BeginningEdit event. I want to run some code that possibly cancels the BeginningEdit event based on the name of the column. For example:

private void tickerGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e) {
    e.Cancel = (string)e.Column.Header != "Name";
}

My DataGridTemplateColumn tag looks like:

<DataGridTemplateColumn Header="Name" IsReadOnly="False">

I would like to store "Name" as a constant somewhere. How can I do this? I tried making a public String property and binding the DataGridTemplateColumn Header like this:

<DataGridTemplateColumn Header="{Binding Path=ColName}" IsReadOnly="False">

but I think the DataContext is different because this didn't work for me.

How can I make a constant string that is available both to my C# code and to a DataGridTemplateColumn Header?


Solution

  • Just try this one (posting based on our previous discussion)...

    Header="{x:Static yourNamespace:Constants.ColName}"

    (And Constants.ColName is based on @mathieu 's answer - just define a class with a static property anywhere in the code - and get the namespace right)

    Basically you don't need Binding as what you have is a const string so simplest thing is just using x:Static. (and you can add properties like that where needed).

    Alternative is also to 'construct' a string object in XAML somewhere and using StaticResources to that. But this seems easier - you can keep a global static class for similar things.