Monday, July 31, 2006

A small tip today on how to access elements that are embedded within a control template. In my case for an itemscontrol class.
Consider the following Xaml:

<ItemsControl

    x:Class="Client.Framework.TijdslijnVisualizer.TijdslijnVisualisatie"

    xmlns:cf="clr-namespace:Client.Framework.TijdslijnVisualizer"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    >

  <ItemsControl.Style>

    <Style TargetType="{x:Type ItemsControl}">

      <Setter Property="Template">

        <Setter.Value>

          <ControlTemplate TargetType="{x:Type ItemsControl}">

            <DockPanel LastChildFill="True">

              <Slider Name="slider" DockPanel.Dock="Right" Minimum="1" Maximum="10" Value="1" Orientation="Vertical" />

              <ScrollViewer Name="scroller" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" CanContentScroll="False">

                <cf:TijdslijnPanel Name="tijdslijnpanel"  IsItemsHost="True" zoomFactor="{Binding ElementName=slider, Path=Value }" />

              </ScrollViewer>

            </DockPanel>

          </ControlTemplate>

        </Setter.Value>

      </Setter>

    </Style>

  </ItemsControl.Style>

</ItemsControl>

 

In the code behind for this class you will not be able to simply get the to these elements with ease. Or at least, not until I realized that these elements were not set yet until the template was actually applied. If you try to find them after that, you will find them through the VisualTreeHelper.GetChild or a simple .FindName:

 

        public override void OnApplyTemplate()

        {

            base.OnApplyTemplate();

 

            this.slider = (Slider) this.Template.FindName("slider", this);

            this.scroller = (ScrollViewer) this.Template.FindName("scroller", this);

 

            // other stuff

        }

 

I hope this helps somebody out there!

 

Wednesday, December 06, 2006 1:00:20 AM (Romance Standard Time, UTC+01:00)
Helped me out a ton. Thanks man. I spent my afternoon looking for how to do this.
Matt
Wednesday, December 06, 2006 8:35:40 PM (Romance Standard Time, UTC+01:00)
Cool, I'm glad!
Ruurd
Friday, May 11, 2007 5:20:09 AM (Romance Standard Time, UTC+01:00)
Thanks, it helped me also.
Aymeric
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):