Wednesday, August 21, 2013

WPF - Access any control inside Template control

Following is code to get the control
[ControlType] objName = ([ControlType])ParentControlName.Template.FindName("ControlName", ParentControlName);


Ex:- 
Below is the code to get the scroll viewer of combo box and set to top

ScrollViewer cmbScrollViewer = ScrollViewer)cmbName.Template.FindName("DropDownScrollViewer", cmbName);

cmbScrollViewer.ScrollToHome();
  

Style Control template of combo box maybe as below

<ControlTemplate TargetType="{x:Type ComboBox}">
…. 
<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"x:Name="DropDownScrollViewer" Template="{DynamicResource ScrollViewerTemplate}" MaxWidth="330"MaxHeight="{TemplateBinding MaxDropDownHeight}">
        <ItemsPresenter/>
</ScrollViewer>
…. 

</ControlTemplate>