1
votes

On a UWP app (Windows 10), I am displaying a list of records in a ListView.

When I click on an item, its StackPanel is displayed (using INotifyPropertyChanged). In the StackPanel, there is a TextBox with some data populated via binding.

I would like that the TextBox automatically receives the focus whenever the StackPanel becomes visible, but I can't find which property or event to use, and how to trigger a textBox.Focus().

Thanks for your feedback on this !

The DataTemplate:

    <DataTemplate x:Key="templateList">
        <StackPanel>
...
            <StackPanel Visibility="{Binding IsSelected}">
                <TextBox x:Name="textBox"
                         Text="{Binding Title, Mode=TwoWay}"/>
...
            </StackPanel>
        </StackPanel>
    </DataTemplate>
...

The ListView:

<ListView x:Name="listView" 
          ItemsSource="{Binding mylist}" 
          ItemTemplate="{StaticResource templateList}"/>
1

1 Answers

2
votes

I can suggest use Behaviors for this case. As I noticed, you use Visibility type for IsSelected property. It means that we can use DataTriggerBehavior and create our SetupFocusAction which implement IAction

public class SetupFocusAction : DependencyObject, IAction
{
    public Control TargetObject
    {
        get { return (Control)GetValue(TargetObjectProperty); }
        set { SetValue(TargetObjectProperty, value); }
    }

    public static readonly DependencyProperty TargetObjectProperty =
        DependencyProperty.Register("TargetObject", typeof(Control), typeof(SetupFocusAction), new PropertyMetadata(0));

    public object Execute(object sender, object parameter)
    {
        return TargetObject?.Focus(FocusState.Programmatic);
    }
}

After that we can use this action in XAML:

xmlns:i="using:Microsoft.Xaml.Interactivity"
xmlns:core="using:Microsoft.Xaml.Interactions.Core"

...

<StackPanel Visibility="{Binding IsSelected}"
            Grid.Row="1">
    <TextBox x:Name="textBox"
                Text="{Binding Title, Mode=TwoWay}">
        <i:Interaction.Behaviors>
            <core:DataTriggerBehavior Binding="{Binding IsSelected}"
                                        ComparisonCondition="Equal"
                                        Value="Visible">
                <local:SetupFocusAction TargetObject="{Binding ElementName=textBox}"/>
            </core:DataTriggerBehavior>
        </i:Interaction.Behaviors>
    </TextBox>
</StackPanel>

enter image description here