Retrieve a TextBox element dinamically created and Focus it
Posted
by user335444
on Stack Overflow
See other posts from Stack Overflow
or by user335444
Published on 2010-05-07T16:52:25Z
Indexed on
2010/05/07
16:58 UTC
Read the original article
Hit count: 298
Hi, I have a collection (VariableValueCollection) of custom type VariableValueViewModel objects binded with a ListView. WPF Follow:
<ListView ItemsSource="{Binding VariableValueCollection}" Name="itemList">
<ListView.Resources>
<DataTemplate DataType="{x:Type vm:VariableValueViewModel}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="180"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBox TabIndex="{Binding Path=Index, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Grid.Column="0" Name="tbValue" Focusable="True" LostFocus="tbValue_LostFocus" GotFocus="tbValue_GotFocus" KeyDown="tbValue_KeyDown">
<TextBox.Text>
<Binding Path="Value" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay">
<Binding.ValidationRules>
<ExceptionValidationRule></ExceptionValidationRule>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</Grid>
</DataTemplate>
</ListView.Resources>
</ListView>
My Goal is to add a new row when I press "enter" on last row, and Focus the new row. To do that, I check that row is the last row and add a new row in that case. But I don't know how to focus the new TextBox...
Here the KeyPressed method:
private void tbValue_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == System.Windows.Input.Key.Enter)
{
DependencyObject obj = itemList.ContainerFromElement((sender as TextBox));
int index = itemList.ItemContainerGenerator.IndexFromContainer(obj);
if( index == (VariableValueCollection.Count - 1) )
{
// Create a VariableValueViewModel object and add to collection. In binding, that create a new list item with a new TextBox
ViewModel.AddNewRow();
// How to set cursor and focus last row created?
}
}
}
Thank's in advance...
© Stack Overflow or respective owner