tags:

views:

310

answers:

1

I have a ListBox which is populated from a collection of ViewModels, which uses in place editing, which I do by having a couple of styles which I can apply to parts of the DataTemplate which make them visible/collapsed as required. These look something like:

<Style
    x:Key="UnselectedVisibleStyle"
    TargetType="{x:Type FrameworkElement}">
    <Setter
        Property="Visibility"
        Value="{Binding Path=IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}, Converter={StaticResource boolToVis}, ConverterParameter=False}" />
</Style>
<Style
    x:Key="SelectedVisibleStyle"
    TargetType="{x:Type FrameworkElement}">
    <Setter
        Property="Visibility"
        Value="{Binding Path=IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}, Converter={StaticResource boolToVis}, ConverterParameter=True}" />
</Style>

With my ListBox having it's ItemTemplate given by something like:

    <ListBox.ItemTemplate>
        <DataTemplate>
             <Grid>                      
                <TextBlock
                    Text="{Binding Name}"
                    Style="{StaticResource UnselectedVisibleStyle}" />
                <TextBox
                    x:Name="textBox"
                    Text="{Binding Name}"
                    Style="{StaticResource SelectedVisibleStyle}" />
             </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>

This works fine, but what I want ideally is to have the TextBox automatically selected when a user clicks the item, ideally in a nice generic way I can use throughout my project, and without too much messing around in my codebehind.

Thanks, DM.

A: 

The following change to your selected Style seemed to work for me:

<Style x:Key="SelectedVisibleStyle" TargetType="{x:Type FrameworkElement}">
    <Setter Property="Visibility" Value="{Binding Path=IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}, Converter={StaticResource boolToVis}, ConverterParameter=True}"/>
    <Style.Triggers>
        <Trigger Property="Visibility" Value="Visible">
            <Setter Property="FocusManager.FocusedElement" Value="{Binding RelativeSource={RelativeSource Self}}"/>
        </Trigger>
    </Style.Triggers>
</Style>
Robert Macnee