[英]Changing TabControl SelectedIndex when adding a new TabItem
I made a button to add a new TabItem in my TabControl.我做了一个按钮来在我的 TabControl 中添加一个新的 TabItem。 It works fine, but i would like the SelectedIndex to be on the new TabItem when i add a new one.
它工作正常,但是当我添加一个新的 TabItem 时,我希望 SelectedIndex 位于新的 TabItem 上。 The code of the
的代码
private void AddNewTabItem(object sender, MouseButtonEventArgs e)
{
...
tabControl.Items.Add(tabItem);
tabControl.SelectedIndex = tabControl.Items.Count - 1;
}
But this doesnt work, because the new TabItem is created after all the function linked to my button click are executed.但这不起作用,因为在执行链接到我的按钮单击的所有函数之后创建了新的 TabItem。 So, when i change the SelectedIndex, the new TabItem is not created yet.
因此,当我更改 SelectedIndex 时,尚未创建新的 TabItem。
I searched for a triggerEvent on the TabControl class, like "WhenItemsChange" but i found nothing.我在 TabControl 类上搜索了一个 triggerEvent,比如“WhenItemsChange”,但我什么也没找到。
Thanks for help, and sorry if this is not clear.感谢您的帮助,如果不清楚,请见谅。
You may create TabItems that are selected by default.您可以创建默认选中的 TabItem。
In case ti
is already a TabItem, just write如果
ti
已经是 TabItem,只需写
ti.IsSelected = true;
tabControl.Items.Add(ti);
If not, assign an appropriate Style to the TabControl's ItemContainerStyle
:如果没有,请为 TabControl 的
ItemContainerStyle
分配适当的 Style :
<TabControl x:Name="tabControl">
<TabControl.ItemContainerStyle>
<Style TargetType="TabItem">
<Setter Property="IsSelected" Value="True"/>
</Style>
</TabControl.ItemContainerStyle>
</TabControl>
Try this:尝试这个:
private void AddNewTabItem(object sender, MouseButtonEventArgs e)
{
...
tabControl.Items.Add(ti);
Dispatcher?.BeginInvoke((Action)(
() => tabControl.SelectedIndex = tabControl.Items.Count - 1));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.