Search code examples
c#wpfxamlwpfdatagrid

WPF DataGrid with RecognizesAccessKey turned off


I have a very basic WPF application with a MS SQL server as data source attached to it. My datagrid is declared as follows:

<DataGrid HorizontalAlignment="Left" Margin="10,88,0,0" VerticalAlignment="Top" Height="456" Width="1018" ItemsSource="{Binding}" />

When I run the app I see the data loaded into the grid from the database, but the column captions look odd. Every caption that originally contains an underscore has this underscore removed: some_title turns to sometitle.

I found out that's because the underscore is recognized as a control symbol to turn the next symbol into a mnemonic.

How can I disable this behavior?

I found out this behavior can be bypassed if you double the single underscores, i.e. some__title instead of some_title. But since my data source is an external database I can't influence that. Or maybe with a converter?

I figured the best approach would be to turn the property RecognizesAccessKey to false, but unfortunately it somehow isn't accessible.

I'm new to WPF, thanks for your help!

P.S. Her is a picture of Snoop (if that helps) DataGrid snooped

edit: my target framework is .net 4.5


Solution

  • The best solution I could come up with is intercepting the DataGrid event AutoGeneratingColumn and replace all underscores with two underscores like this:

    private void DataGrid_AutoGeneratingColumn_1(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        string header = e.Column.Header.ToString();
    
        // Replace all underscores with two underscores, to prevent AccessKey handling
        e.Column.Header = header.Replace("_", "__");
    }
    

    In my understanding it is (sadly) not possible to override the value of RecognizesAccessKey of the underlying ContentPresenter without redefining the whole control template. See this thread on the msdn forums: How to set RecognizesAccessKey on labels without influencing other parameters?.