Thursday, March 29, 2007
Selecting Editable Items in an .net WPF ListBox (or ComboBox)
What could be simpler than selecting items from a WPF ListBox. You can even make the items have fancy formating using a TextBlock. If you want to allow the user to edit the ListBox items then there is a problem. This occurs when your ListBox items are editable objects, such as a TextBox. Selecting around the TextBox selects the appropriate ListBox item, but selecting the TextBox only selects the TextBox.
The solution to this problem is when the TextBox is selected, to also select the ListBox item. To this you need to setup an event handler and write a few lines of C# code. You want use the "GotFocus" event since the TextBox may be selected by multiple methods such as tabbing with the keyboard or clicking with the mouse.
To make things simpler you can use Expression Blend to setup the event handler and create C# shell code. To do this select the TextBox properities using Expression Blend and then select the event handlers.
Here is a C# event handler for the TextBox, which is any item in ListBox for this example.
Where the ListBox is defined as
with a template like this
The solution to this problem is when the TextBox is selected, to also select the ListBox item. To this you need to setup an event handler and write a few lines of C# code. You want use the "GotFocus" event since the TextBox may be selected by multiple methods such as tabbing with the keyboard or clicking with the mouse.
To make things simpler you can use Expression Blend to setup the event handler and create C# shell code. To do this select the TextBox properities using Expression Blend and then select the event handlers.
Here is a C# event handler for the TextBox, which is any item in ListBox for this example.
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
TextBox tb = sender as TextBox;
if (tb == null) return;
if (tb.DataContext == null) return;
this.listBoxDataItems.SelectedItem = tb.DataContext;
}
Where the ListBox is defined as
ItemsSource="{Binding Path=CodeCreatorData}"
x:Name="listBoxDataItems" />
with a template like this
GotFocus="TextBox_GotFocus"/>
Subscribe to Posts [Atom]
