Selelect ListBoxItem when focus TextBox inside ItemTemplate #11208
-
Considering following code:
I would like the ListBoxItem to be selected when activating the Textbox. How can I do? Avalonia Version: 11.0.0-preview7 |
Beta Was this translation helpful? Give feedback.
Answered by
timunie
May 3, 2023
Replies: 1 comment 1 reply
-
You could use an EventHandler for TextBox.GotFocus which sets SelectedItem on parent ListBox like this: ! <!-- Do NOT place ListBox inside StackPanel as it will break virtualization -->
<DockPanel LastChildFill="True">
<TextBlock Text="{Binding Greeting}"
DockPanel.Dock="Top"/>
<ListBox ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Name}"
+ GotFocus="TextBox_OnGotFocus"
Margin="5"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DockPanel> and in the event handler: private void TextBox_OnGotFocus(object? sender, GotFocusEventArgs e)
{
// Test if the sender is a TextBox. If so, try to find an ancestor of type ListBox
if (sender is TextBox tb && tb.FindAncestorOfType<ListBox>() is { } lb)
{
// Set the selected item of our ListBox to the DataContext of our TextBox
lb.SelectedItem = tb.DataContext;
}
} Note: If you want this to be applied in several places, you can also wirte a behavior which can be attached easily. |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
workgroupengineering
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You could use an EventHandler for TextBox.GotFocus which sets SelectedItem on parent ListBox like this:
and in the event handler: