将焦点设置在 WPF 中 ControlTemplate 内的控件上

2023-12-01

在我正在开发的应用程序中,我们有一堆自定义控件,其 ControlTemplates 在 Generic.xaml 中定义。

例如,我们的自定义文本框看起来类似于:

<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 上。

我想出的最佳解决方案是在每个控件模板中的主控件上设置一个名称(在本例中为 TextBox),例如“FocusableControl”。

然后将焦点设置在控件上的我的代码(包含在 FieldTextBox 的代码隐藏中)将是:

    Control control = (Control)this.Template.FindName("FocusableControl", this);
    if (control != null)
    {
        control.Focus();
    }

这个解决方案有效。但是,还有其他人知道比这更有效的解决方案吗?


在控件模板中,您可以添加一个触发器来设置 StackPanel 的 FocusedElement焦点管理器到您想要聚焦的文本框。您将触发器的属性设置为 {TemplateBinding IsFocused},以便在包含控件获得焦点时触发。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将焦点设置在 WPF 中 ControlTemplate 内的控件上 的相关文章

随机推荐