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,
- <Grid>
- <Button Height="39" Width="100" Content="_Save"/>
- </Grid>
Now, tweak the code a bit and instead of setting content directly on a button, do it on ContentPresenter, as shown below.
- <Grid>
- <Button Width="95" Height="34" Background="Orange">
- <Button.Template>
- <ControlTemplate TargetType="Button">
- <Grid>
- <Rectangle Fill="{TemplateBinding Background}"/>
- <ContentPresenter Content="{TemplateBindingContent}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
- </Grid>
- </ControlTemplate>
- </Button.Template>
- _Save
- </Button>
- </Grid>
The question is, how to get this underscore at the proper location, below S?
No worries! A simple property, RecognizesAccessKey does this for you.
- <Grid>
- <Button Width="95" Height="34" Background="Orange">
- <Button.Template>
- <ControlTemplate TargetType="Button">
- <Grid>
- <Rectangle Fill="{TemplateBinding Background}"/>
- <ContentPresenter RecognizesAccessKey="True" Content="{TemplateBindingContent}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
- </Grid>
- </ControlTemplate>
- </Button.Template>
- _Save
- </Button>
- </Grid>
Happy coding!!!

Anu VPosted Dec 28, 2016, 11:06 PM
Nice article thanks for sharing..