AccessKey Not Working On WPF ContentPresenter

Recently, I received a query from one of my friends, stating that the access key wasn't working in his WPF project when he was using ContentPresenter. So, I thought to share a post on it as it may be helpful for other readers also. Before digging directly into the problem, first, let’s see what happens when access key is set directly on content property of a WPF Button.

Below is my code for setting Content on a Button,

  1. <Grid>  
  2.         <Button Height="39" Width="100" Content="_Save"/>  
  3. </Grid>   
If you run your application with the above snippet, you will notice that there is no underscore coming in front of the word "Save". But as soon as you press the "Alt" key, underscore comes up. Which is an expected behavior :)
Now, tweak the code a bit and instead of setting content directly on a button, do it on ContentPresenter, as shown below.
  1. <Grid>  
  2.         <Button Width="95" Height="34" Background="Orange">  
  3.             <Button.Template>  
  4.                 <ControlTemplate TargetType="Button">  
  5.                     <Grid>  
  6.                         <Rectangle Fill="{TemplateBinding Background}"/>  
  7.                         <ContentPresenter Content="{TemplateBindingContent}" HorizontalAlignment="Center" VerticalAlignment="Center"/>  
  8.                     </Grid>  
  9.                 </ControlTemplate>  
  10.             </Button.Template>  
  11.             _Save  
  12.         </Button>  
  13. </Grid>  
Now, if you run your application with the above snippet, you will get an output in which underscore comes at an incorrect place, which is before S.

The question is, how to get this underscore at the proper location, below S?

No worries! A simple property, RecognizesAccessKey does this for you.
  1. <Grid>  
  2.   <Button Width="95" Height="34" Background="Orange">  
  3.      <Button.Template>  
  4.         <ControlTemplate TargetType="Button">  
  5.          <Grid>  
  6.             <Rectangle Fill="{TemplateBinding Background}"/>   
  7.     <ContentPresenter RecognizesAccessKey="True" Content="{TemplateBindingContent}" HorizontalAlignment="Center" VerticalAlignment="Center"/>  
  8.         </Grid>  
  9.        </ControlTemplate>  
  10.      </Button.Template>  
  11. _Save  
  12.   </Button>  
  13. </Grid>  
And that's it! We are done. Now, if you run your application, you will see the underscore under S, which is the expected output.

Happy coding!!!

 

Ebook Download
View all
Learn
View all