0

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!

Florian
  • 1,019
  • 6
  • 22
  • Perhaps something like: ```this.ListViewItems.SelectedIndex = this.ListViewItems.Items.Count - 1;``` – Etheraex Jun 07 '22 at 13:26

2 Answers2

0

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>
Timvr01
  • 476
  • 4
  • 15
  • See also https://stackoverflow.com/questions/1356045/set-focus-on-textbox-in-wpf-from-view-model – Timvr01 Jun 07 '22 at 13:32
0

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

Florian
  • 1,019
  • 6
  • 22