I have what I am sure is an extremely common requirement, but Googling around has so far failed to leave me any wiser about the neatest way to make the items of a
ListBox
editable in-place.
Note that I do still require the notion of a currently-selected item for the items in the list.
I have a
ListBox
defined as follows:
<DataTemplate x:Key="DataTemplateContact">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="Name:"/>
<TextBox Grid.Row="0" Grid.Column="1" Text="{Binding FullName}"/>
<TextBlock Grid.Row="1" Grid.Column="0" Text="Telephone:"/>
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding MainTelephoneNumber}"/>
</Grid>
</DataTemplate>
<ListBox ItemsSource="{Binding Contacts}" ItemTemplate="{StaticResource DataTemplateContact}"/>
If I click on a 'dead' part of an item, the WPF selection-changed mechanism kicks in and sets the currently-selected item, which is great. The problem is if I click on either of the
TextBox
controls. I can begin typing in these boxes, but as far as I can tell, WPF doesn't seem to be aware that I am doing anything.
If I set
IsEnabled="False"
on the
TextBox
fields then this fixes part of the problem. If I click on a
TextBox
, WPF recognises that the currently-selected item has changed and this is set accordingly in my View-Model. The problem then becomes how to tell when the currently-being-edited item in the
ListBox
loses focus.
Can anyone please point me at a neat solution? Can I maybe do something using triggers?
Any help at all would be very much appreciated.
Kind wishes ~ Patrick
What I have tried:
I have half-cobbled something together by handling loads of events in the UI (e.g.
ListBox.SelectionChanged
,
ListBox.MouseDoubleclick
, and trying to catch clicks anywhere else in the window), but this all feels very scruffy and puts an uncomfortable amount of logic in my XAML code-behind file.
I have recently tried this:
<Style x:Key="TestStyle" TargetType="TextBox">
<Setter Property="Focusable" Value="False"/>
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}}, Path=IsSelected}" Value="True">
<Setter Property="Background" Value="Crimson"/>
<Setter Property="Focusable" Value="True"/>
</DataTrigger>
</Style.Triggers>
</Style>
The crimson colour is set okay but the TextBox doesn't become editable. Could anyone please explain why?