Tuesday, December 27, 2016

AccessKey not working on WPF ContentPresenter

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

Below is my code for setting a Content on a Button:
<Grid>
        <Button Height="39" Width="100" Content="_Save"/>
</Grid>

If you will run your application with above snippet, you will notice that there is no underscore coming in front of word Save. But as soon as you press 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:
<Grid>
        <Button Width="95" Height="34" Background="Orange">
            <Button.Template>
                <ControlTemplate TargetType="Button">
                    <Grid>
                        <Rectangle Fill="{TemplateBinding Background}"/>
                        <ContentPresenter Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                    </Grid>
                </ControlTemplate>
            </Button.Template>
            _Save
        </Button>
</Grid>
Now, if you will run your application with above snippet, you will get an output in which underscore is coming at incorrect place, which is before S.

Question is how to get this underscore at 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="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
        </Grid>
       </ControlTemplate>
     </Button.Template>
_Save
  </Button>
</Grid>

And that's it, we are done. Now if you will run your application, you will see the underscore under S, which is the expected output.
Happy coding!!!

No comments:

Post a Comment