How to determine if an item is the last one in a WPF ItemTemplate?
Posted
by Mike
on Stack Overflow
See other posts from Stack Overflow
or by Mike
Published on 2010-03-20T16:40:52Z
Indexed on
2010/03/20
16:51 UTC
Read the original article
Hit count: 427
Hi everyone,
I have some XAML
<ItemsControl Name="mItemsControl">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Mode=OneWay}" KeyUp="TextBox_KeyUp"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
that's bound to a simple ObservableCollection
private ObservableCollection<string> mCollection = new ObservableCollection<string>();
public MainWindow()
{
InitializeComponent();
this.mCollection.Add("Test1");
this.mCollection.Add("Test2");
this.mItemsControl.ItemsSource = this.mCollection;
}
Upon hitting the enter key in the last TextBox, I want another TextBox to appear. I have code that does it, but there's a gap:
private void TextBox_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key != Key.Enter)
{
return;
}
TextBox textbox = (TextBox)sender;
if (IsTextBoxTheLastOneInTheTemplate(textbox))
{
this.mCollection.Add("A new textbox appears!");
}
}
The function IsTextBoxTheLastOneInTheTemplate() is something that I need, but can't figure out how to write. How would I go about writing it?
I've considered using ItemsControl.ItemContainerGenerator, but can't put all the pieces together.
Thanks!
-Mike
© Stack Overflow or respective owner