Category Archives: WPF

‘Target’ Attribute in WPF

This short article is going to explain the usefulness of ‘Target’ attribute in WPF. Keep in your mind is that Target attribute is used to set focus on an element in the WPF Window when the access key associated with the element is hit. In other words, Target attributes is used to set focus on another element associated with the current element when the access key is hit. For example, let us build a Window with Label and TextBox

clip_image002

<Window x:Class="WPFTester.BindingAndReference"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;

        xmlns:d="http://schemas.microsoft.com/expression/blend/2008&quot;

        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006&quot;

        xmlns:local="clr-namespace:WPFTester"

        mc:Ignorable="d"

        Title="BindingAndReference" Height="300" Width="300">

    <StackPanel>

        <Label FontSize="16">Enter text:</Label>

        <TextBox x:Name="txtName" FontSize="16"></TextBox>

    </StackPanel>

</Window>

Now, we are going to create an access key (for example, Alt + t) which when it is hit, the cursor will be set in the text box directly. To do that we need to set the attribute ‘Target’ of the label, so that when Alt + t is hit, the focus will be on the TextBlock, so that the user can enter his or her name. XAML code will be modified to look like follow:

<Window x:Class="WPFTester.BindingAndReference"

        

       

    <StackPanel>

        <Label Target="{Binding ElementName=txtName}" FontSize="16">Enter _text:</Label>

        <TextBox x:Name="txtName" FontSize="16"></TextBox>

    </StackPanel>

</Window>

The modified or added code has been highlighted, the rest of the previous code is intact. The label is bound to the TextBox through Target attribute of the label. Note that ElementName refers to the element name associated with its label. To set a name to a control, use ‘x:Name’. Note, to set the access key use the symbol ‘_’ before the letter that you need to associate it with Alt combination.

clip_image004

%d مدونون معجبون بهذه: