Reputation: 5211
Initially I thought that it will be a very trivial functionality but now I am not able to implement it.
My requirement is simple. I am programmatically setting the content of a TabItem
. The content will be usercontrols. I want to set the text of the header of the TabItem
based on the content.
Content doesn’t have a changed event so I am confused as to on which event should I write code.
Also I’m not able to find any style or anything on the net.
Any suggestions? Please help. Thanks in advance.
PS: Please let me know if you need any further information from my side.
Upvotes: 1
Views: 1056
Reputation: 4002
TabControl XAML:
<TabControl Name="myTabControl" >
<TabItem Header="myHeader" Name="myTabItem">
<my:customUserControl />
</TabItem>
</TabControl>
Binding the TabItem
Header property in code:
// 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);
Upvotes: 0
Reputation: 5211
I think i got it. Not sure if this is the optimum solution so if anybody has a better solution than this then it will help me a lot.
I made a custom tabitem and overrided OnContentChanged
(Didnt knew that there is an overridable OnContentChanged
:)). So my code is like below.
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); } }
Upvotes: 0
Reputation: 2133
Updated:
You can also use DependencyPropertyDescriptor.AddValueChanged
method. see:
system.componentmodel.dependencypropertydescriptor.addvaluechanged.aspx
see: wpf-why-is-there-no-isreadonlychanged-event-on-textbox-controls
also see this link: listening-to-dependencyproperty-changes
My old answer:
Create a custom class and handle OnPropertyChanged event. Sth like this:
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
}
}
}
Upvotes: 1
Reputation: 50752
If you are using MVVM(or building tabs by assigning TabControl.ItemsSource
) it is simple to do, just define an ItemTemplate
:
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text={Bindin Name}/>
</DataTemplate>
</TabControl.ItemTemplate>
Upvotes: 1