Search code examples
silverlightbindingtelerikdatatemplateancestor

Access DataTemplate Property


I have a TabControl with a custom ItemTemplate (for the TabItem).

I would like to hide the last tab item and if I could bind to the TabItem's Visibility property this would be possible.

Any suggestions?


Solution

  • I figured out a way to do this with a behavior. I would have preferred a cleaner solution such as a binding, but it works.

         <telerik:RadTabControl x:Name="myRadTabControl">
           <telerik:RadTabControl.ItemTemplate>
                <!-- Tab Item Header -->
                <DataTemplate>
                    <TextBlock>
                        <i:Interaction.Behaviors>
                            <Behaviors:MakeLastTabItemInvisible ParentRadTabControl="{Binding ElementName=myRadTabControl}" />
                        </i:Interaction.Behaviors>
                     </TextBlock>
                </DataTemplate>
            </telerik:RadTabControl>
          </telerik:RadTabControl x:Name="myRadTabControl">
    
    public class MakeLastTabItemInvisible : Behavior<FrameworkElement>
    {
        #region ParentRadTabControl Dependency Property
    
        /// <summary>
        /// ParentRadTabControl
        /// </summary>
        public RadTabControl ParentRadTabControl
        {
            get { return (RadTabControl)GetValue(ParentRadTabControlProperty); }
            set { SetValue(ParentRadTabControlProperty, value); }
        }
    
        /// <summary>
        /// ParentRadTabControl Dependency Property.
        /// </summary>
        public static readonly DependencyProperty ParentRadTabControlProperty =
            DependencyProperty.Register(
                "ParentRadTabControl",
                typeof(RadTabControl),
                typeof(MakeLastTabItemInvisible),
                new PropertyMetadata(new PropertyChangedCallback(ParentRadTabControlChanged)));
    
        private static void ParentRadTabControlChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            MakeLastTabItemInvisible c = d as MakeLastTabItemInvisible;
            if (c != null)
            {
                if (e.NewValue == null) return;
    
                var parentTabControl = (RadTabControl)e.NewValue;
                if (parentTabControl.Items.Count <= 0) return;
    
                var lastTabItem = parentTabControl.ItemContainerGenerator.ContainerFromIndex(parentTabControl.Items.Count - 1) as RadTabItem;
    
                if (lastTabItem != null) lastTabItem.Visibility = Visibility.Collapsed;
            }
        }
    
        #endregion
    }