我正在制作一个窗口,显示用户的多个选项,每个选项都有一个无线电按钮和一个文本框。
打开此窗口时,焦点应放在与打开窗口时选中的无线电按钮对应的文本框上(这都是预设的,无需担心)。
在xaml或代码隐藏中修复它是重要的。
我使用了一个DataTrigger将FocusedElement更改为右边的textbox,但是它在设置之后就会被覆盖。
相关代码在下面的DataTrigger中。颜色被正确地更改,但是FocusElement没有。
我已经尝试了所有的选项,我已经找到了堆栈溢出和谷歌。问题不在于DataTrigger或FocusedElement的设置。我认为这是因为它最终被推翻了。我已经使用Snoop查看了Keyboard.FocusedElement中的更改,并且它没有显示任何更改。
<DataTemplate x:Uid="DataTemplate_1" >
<RadioButton x:Uid="RadioButton_1" GroupName="Options" IsChecked="{Binding IsSelected}" Margin="4,0,0,0" Name="RadioBtn">
<StackPanel x:Uid="StackPanel_1" Orientation="Horizontal" >
<Label x:Uid="Label_1" Visibility="{Binding IsUserInput, Converter={cs:OppositeVisibilityConverter}}" Content="{Binding Description, Mode=OneWay}" />
<Label x:Uid="Label_2" Visibility="{Binding IsUserInput, Converter={cs:VisibilityConverter}}" Content="Anders, nl: " />
<TextBox x:Uid="MemAnders" Visibility="{Binding IsUserInput, Converter={cs:VisibilityConverter}}" Text="{Binding AlternativeText}"
Name="MemAnders" MinWidth="400" IsTabStop="False"
>
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsSelected}" Value="True">
<Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=MemAnders}"/>
<Setter Property="Background" Value="LightGoldenrodYellow" />
</DataTrigger>
<DataTrigger Binding="{Binding IsSelected}" Value="False">
<Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=RadioBtn}"/>
<Setter Property="Background" Value="LightBlue" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
</StackPanel >
</RadioButton >
</DataTemplate >与选中的无线电按钮对应的文本框应聚焦。而另一个(父母?)对象是聚焦的。
有人知道解决办法吗?
发布于 2019-07-23 08:09:43
工作结果是将焦点设置为Window_Loaded函数中的textbox。
我使用了Find a WPF element inside DataTemplate in the code-behind提供的算法来找到正确的textbox元素。然后我做了TextBox.Focus();然后就修复了它。
https://stackoverflow.com/questions/57058444
复制相似问题