在我正在开发的应用程序中,我们有一堆自定义控件,其 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();
}
这个解决方案有效。但是,还有其他人知道比这更有效的解决方案吗?