views:

474

answers:

0

I've got a ListView that displays different kinds of items. One of those has a textbox I want to set the focus to. I use a DataTemplateSelector to select the DataTemplate for each item.

This question explains how to set the focus on a textbox in a DataTemplate. But, in this case the DataTemplate is definded directly on the ListView. In my case this doesn't work and I get an Invalid Operation Exception telling me the DateTemplate hasn't been applied (I think it is, because I can see the different templates when running the application and when debugging with mole).

I have to set the focus from code, because it's only visible when the textbox is not empty or has focus.

How can I set the focus to this textbox?

Edit: As requested a few snippets of code. It is impossible to post the whole thing, it contains lots of animations, styling and triggers.

Part of the ListView definition:

<ListView 
    ItemsSource="{Binding Path=Regels,
                          Mode=Default,
                          Source={StaticResource DataModel}}"
    x:Name="ListViewRegels" 
          ...
    ItemContainerStyle=
        "{DynamicResource RegelsContainerStyle}" />

Part of the style:

<Style x:Key="RegelsContainerStyle" TargetType="{x:Type ListViewItem}">
    <Setter Property="ContentTemplateSelector" >
        <Setter.Value>
            <commands:RegItemTemplateSelector />
        </Setter.Value>
    </Setter>
    ...
</Style>

Part of the DataTemplate used for the "Regel" type which is causing the difficulties:

<DataTemplate x:Key="RegelsTemplate" >
  <Grid x:Name="grid">
    <Border x:Name="LayoutRoot" />
      <Grid Background="{x:Null}" x:Name="TheGrid">
      ...
        <Grid x:Name="MemoGrid">
          <TextBox Text="{Binding Path=RegelMemo}" 
                   AcceptsReturn="True" 
                   AcceptsTab="True" 
                   Style="{DynamicResource MemoTextBoxStyle}" 
                   x:Name="MemoTextBox"/>
        </Grid>
      </Grid>
    </Border>
  </Grid>
  ...
</DataTemplate>

Part of the DataTemplateSelector code:

public class RegItemTemplateSelector : DataTemplateSelector
{
    public override DataTemplate
        SelectTemplate(object item, DependencyObject container)
    {
        if (item == null) return null;
        Window window = System.Windows.Application.Current.MainWindow;
        if (item is RegelTypeA)
        {
            return window.FindResource("RegelsTemplate") as DataTemplate;
        }
        ...
        return null;
    }
}