Home > front end >  How is it possible to set the focus on the last item of a DataTemplate?
How is it possible to set the focus on the last item of a DataTemplate?

Time:06-07

How is it possible to set the focus (from c#-code behind or xaml itself) to the last item of my DataTemplate?

That is my XAML code:

<ItemsControl x:Name="ListViewItems">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Border Margin="1 10 0 10" 
                    Height="60">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>
                    <TextBox Grid.Column="0"  
                             x:Name="SsidTextBox"
                             Text="{Binding Ssid, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" >
                    </TextBox>
                    <TextBox Grid.Column="1" 
                             x:Name="PasswordTextBox"
                             Text="{Binding Password, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}">
                    </TextBox>
                </Grid>
            </Border>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

By the way: A new item is generated when I click on a button.

Thanks!

CodePudding user response:

You can use a this attached property:

public static class FocusExtension
{
    public static bool GetIsFocused(DependencyObject obj)
    {
        return (bool) obj.GetValue(IsFocusedProperty);
    }

    public static void SetIsFocused(DependencyObject obj, bool value)
    {
        obj.SetValue(IsFocusedProperty, value);
    }

    public static readonly DependencyProperty IsFocusedProperty =
        DependencyProperty.RegisterAttached(
            "IsFocused", typeof (bool), typeof (FocusExtension),
            new UIPropertyMetadata(false, OnIsFocusedPropertyChanged));

    private static void OnIsFocusedPropertyChanged(
        DependencyObject d, 
        DependencyPropertyChangedEventArgs e)
    {
        var uie = (UIElement) d;
        if ((bool) e.NewValue)
        {
            uie.Focus(); // Don't care about false values.
        }
    }
}

And then add this to the element you want to focus on:

 <TextBox Grid.Column="0" local:FocusExtension.IsFocused="{Binding SsidFocus}" x:Name="SsidTextBox" Text="{Binding Ssid, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" ></TextBox>

CodePudding user response:

Thanks for your suggestions but they did not worked for me.

But it works to use FocusManager:

FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}"

See also: Set the focus on a textbox in xaml wpf

  • Related