私が取り組んでいるアプリケーションには、Generic.xamlで定義されたControlTemplatesを備えた一連のカスタムコントロールがあります。
たとえば、カスタムテキストボックスは次のようになります。
<Style TargetType="{x:Type controls:FieldTextBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type controls:FieldTextBox}">
<Border BorderThickness="0" Margin="5">
<StackPanel ToolTip="{Binding Path=Field.HintText, RelativeSource={RelativeSource TemplatedParent}}">
<TextBlock Text="{Binding Path=Field.FieldLabel, RelativeSource={RelativeSource TemplatedParent}}"
HorizontalAlignment="Left"
/>
<TextBox Width="{Binding Path=Field.DisplayWidth, RelativeSource={RelativeSource TemplatedParent}}"
HorizontalAlignment="Left"
Text="{Binding Path=Field.Data.CurrentValue, RelativeSource={RelativeSource TemplatedParent}}"
IsEnabled="{Binding Path=Field.IsEnabled, RelativeSource={RelativeSource TemplatedParent}}"
ContextMenu="{Binding Source={StaticResource FieldContextMenu}}" >
<TextBox.Background>
<SolidColorBrush Color="{Binding Path=Field.CurrentBackgroundColor, RelativeSource={RelativeSource TemplatedParent}}"/>
</TextBox.Background>
</TextBox>
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Focusable" Value="True" />
<Setter Property="IsTabStop" Value="False" />
</Style>
このアプリケーションでは、ControlTemplate内の特定のコントロールにプログラムでフォーカスを設定できる必要があります。
C#コード内で、データに基づいて特定の「FieldTextBox」にアクセスできます。正しいFieldTextBoxを取得したら、ControlTemplate内に含まれる実際のTextBoxにフォーカスを設定できるようにする必要があります。
私が思いついた最善の解決策は、「FocusableControl」など、各コントロールテンプレート(この場合はTextBox)のプライマリコントロールに名前を設定することです。
次に、コントロールにフォーカスを設定するための私のコード(FieldTextBoxの分離コードに含まれています)は次のようになります。
Control control = (Control)this.Template.FindName("FocusableControl", this);
if (control != null)
{
control.Focus();
}
このソリューションは機能します。しかし、これよりも効率的な解決策を知っている人はいますか?