gpt4 book ai didi

c# - 在 WPF 的 ControlTemplate 中将焦点设置在控件上

转载 作者:行者123 更新时间:2023-11-30 17:25:05 24 4
gpt4 key购买 nike

在我正在处理的应用程序中,我们有一堆自定义控件,它们的 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 的 FocusManager 的 FocusedElement。到您想要聚焦的文本框。您将 Trigger 的属性设置为 {TemplateBinding IsFocused},以便在包含控件获得焦点时触发它。

关于c# - 在 WPF 的 ControlTemplate 中将焦点设置在控件上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/158536/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com