WPF TabBarControl 在选项卡更改时将焦点设置到元素
我有一个绑定到视图模型的 TabControl
<TabControl
ItemsSource="{Binding Path=ViewModelCollection}" >
<TabControl.ItemContainerStyle>
<Style
TargetType="TabItem"
BasedOn="{StaticResource {x:Type TabItem}}">
<Setter
Property="Header"
Value="{Binding Title}" />
<Setter
Property="Content"
Value="{Binding}" />
</Style>
</TabControl.ItemContainerStyle>
</TabControl>
每个选项卡只包含一个视图模型项。我使用数据模板来显示它。
<!-- View Model Template -->
<DataTemplate
DataType="{x:Type local:ViewModelItem}">
<DockPanel>
<TextBox Text="I want this to have the focus"/>
</DockPanel>
</DataTemplate>
当当前选项卡更改时,我希望焦点位于数据模板中的文本框(这是一个简单的示例,在我的生产代码中我有一个数据网格)。我该如何做到这一点?
I have a TabControl that is bound to a view model
<TabControl
ItemsSource="{Binding Path=ViewModelCollection}" >
<TabControl.ItemContainerStyle>
<Style
TargetType="TabItem"
BasedOn="{StaticResource {x:Type TabItem}}">
<Setter
Property="Header"
Value="{Binding Title}" />
<Setter
Property="Content"
Value="{Binding}" />
</Style>
</TabControl.ItemContainerStyle>
</TabControl>
Each Tab simply contains a View Model Item. I use a data template to display this.
<!-- View Model Template -->
<DataTemplate
DataType="{x:Type local:ViewModelItem}">
<DockPanel>
<TextBox Text="I want this to have the focus"/>
</DockPanel>
</DataTemplate>
When the current tab is changed i want the focus to be on the textbox (this is a simple example, in my production code i have a datagrid) in the data template. how do i accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不完全确定当您在 DataTemplate 中定义了模板时,您可以将焦点设置在 UIElement 上。您可以将 DataTemplate 的内容放在 UserControl 中,然后按程序将焦点设置在 TextBox 上,而不是直接使用 DataTemplate。
在 UserControl 的代码隐藏中:
我开发了一个小项目,通过将 DataTemplate 推入 UserControl,当选项卡更改时,TextBox 获得了焦点。
I'm not entirely sure you can set the focus on a UIElement when you have the template defined in a DataTemplate. Instead of working directly with the DataTemplate, you could place your DataTemplate's contents in a UserControl and then set the focus on your TextBox procedurally.
And in the Code Behind of the UserControl:
I worked up a small project and by pushing the DataTemplate into the UserControl, the TextBox gained focus when the tab was changed.