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>

Wednesday, August 7, 2013

C# - How to get Property Name as string by Property Type

Create a static class for Property Helper with GetPropertyName method

public static class PropertyHelper<T>
    {
        public static string GetPropertyName<TPropObject>(Expression<Func<T, TPropObject>> propertyValue)
        {
            return ((MemberExpression)propertyValue.Body).Member.Name;
        }
    }


Call like below to get the PropertyName as string


PropertyHelper<YourClass>.GetPropertyName(r => r.YourProperty)