3

私が取り組んでいるアプリケーションには、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();
    }

このソリューションは機能します。しかし、これよりも効率的な解決策を知っている人はいますか?

4

2 に答える 2

2

コントロールテンプレート内で、StackPanelのFocusManagerのFocusedElementをフォーカスするテキストボックスに設定するトリガーを追加できます。Triggerのプロパティを{TemplateBindingIsFocused}に設定して、含まれているコントロールがフォーカスされたときに起動するようにします。

于 2008-10-01T16:47:19.067 に答える
0

いくつかのDependancyPropertyを提供することにより、コード内のコントロール名のハードコーディングを取り除くことができ、DependancyPropertyに基づくcontrolLoadedまたはOnApplyTemplate関数に同じコードを含めることができます。このDependancyPropertyの送信者は、.Focus()呼び出しの候補になります。

于 2008-10-01T16:47:48.330 に答える