根据wpf中的内容设置tabitem的标题
起初我认为这将是一个非常琐碎的功能,但现在我无法实现它 我的要求很简单。我正在以编程方式设置根据wpf中的内容设置tabitem的标题,wpf,user-controls,wpf-controls,tabitem,Wpf,User Controls,Wpf Controls,Tabitem,起初我认为这将是一个非常琐碎的功能,但现在我无法实现它 我的要求很简单。我正在以编程方式设置TabItem的内容。内容将是用户控件。我想根据内容设置TabItem标题的文本 内容没有更改的事件,所以我不知道应该在哪个事件上编写代码 而且我在网上找不到任何风格或任何东西 有什么建议吗?请帮忙。提前谢谢 PS:如果您需要我方的任何进一步信息,请告诉我。如果您正在使用MVVM(或通过分配TabControl.ItemsSource来构建选项卡),操作简单,只需定义ItemTemplate: <T
TabItem
的内容。内容将是用户控件。我想根据内容设置TabItem
标题的文本
内容没有更改的事件,所以我不知道应该在哪个事件上编写代码
而且我在网上找不到任何风格或任何东西
有什么建议吗?请帮忙。提前谢谢
PS:如果您需要我方的任何进一步信息,请告诉我。如果您正在使用MVVM(或通过分配TabControl.ItemsSource
来构建选项卡),操作简单,只需定义ItemTemplate
:
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text={Bindin Name}/>
</DataTemplate>
</TabControl.ItemTemplate>
更新:
您还可以使用
DependencyPropertyDescriptor.AddValueChanged
方法。见:
见:
另请参见此链接:
我以前的答案:创建自定义类并处理OnPropertyChanged事件。像这样的事情:
public class MyTabItem : TabItem
{
public MyTabItem() { }
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
if (e.Property.ToString() == "Content")
{
// here you are sure that ContentPropertyhas changed
}
}
}
我想我明白了。不确定这是否是最佳解决方案,所以如果有人有比这更好的解决方案,那么这将对我有很大帮助 我制作了一个自定义选项卡项并覆盖了
OnContentChanged
(我不知道有一个可覆盖的OnContentChanged
:)。我的代码如下所示
public class TabItemData : TabItem
{
protected override void OnContentChanged(object oldContent, object newContent)
{
if (newContent.GetType().Name.ToLower().Contains("mycontrolname"))
this.Header = "control name";
else
this.Header = "old name";
base.OnContentChanged(oldContent, newContent);
}
}
公共类TabItemData:TabItem
{
受保护的覆盖无效OnContentChanged(对象oldContent、对象newContent)
{
if(newContent.GetType().Name.ToLower().Contains(“mycontrolname”))
this.Header=“控件名称”;
其他的
this.Header=“旧名称”;
base.OnContentChanged(旧内容、新内容);
}
}
TabControl XAML:
<TabControl Name="myTabControl" >
<TabItem Header="myHeader" Name="myTabItem">
<my:customUserControl />
</TabItem>
</TabControl>
请提供您已经尝试过的任何代码/xaml。在设置选项卡项的内容时,为什么不设置标题的内容?@Ron;我可以这样做,但内容设置在多个地方,所以我必须重复代码设置在多个地方。此外,如果添加了任何其他usercontrol,那么开发人员将有额外的负担,需要记住添加代码。实际上,我只是将usercontrol对象分配给内容。Tabcontrol中已经有一个以xaml格式硬编码的tabitem。类似于“tabitem1.Content=objUserControl;”的内容,因此我们不会将任何ItemsSource分配给tabcontrol:(比显示一些代码请,我相信这是可能的处理太多,我只需要看到一些代码
// Bind TabItem Header
// Create a binding to a "Header" property in your ViewModel
Binding myBinding = new Binding("Header");
// Set the Source of the binding to your ViewModel
myBinding.Source = myViewModel;
// Assign the Binding to your TabItem Header property
myTabItem.SetBinding(Expander.HeaderProperty, myBinding);