Category: "Example Codes"
WPF: How to access a control in style
Source:Open Clip Art Using Under Public Domain Attribution
I got a control in style template at one of my custom controls, Like this:
<Style TargetType="{x:Type advgenControls:CollapsibleControl}" x:Key="LeftPanel">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type advgenControls:CollapsibleControl}">
<Grid>
<ContentPresenter x:Name="PART_ContentPresenter"/>
<ResizeGrip Grid.Row="1" HorizontalAlignment="Stretch" Width="Auto" Height="Auto" HorizontalContentAlignment="Right" Margin="0,0,2,2"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I just want to call that "PART_ContentPresenter". But that is xaml living in resources.
That is easy I can use GetTemplateChild("PART_ContentPresenter" ) and call at the OnApplyTemplate(). Please remember don't use it at OnInitialized(EventArgs e). At that time, styles has not loaded yet, you get a null object.:
Code
public override void OnApplyTemplate() | |
{ | |
base.OnApplyTemplate(); | |
if (this.IsInitialized) | |
{ | |
ContentPresenter cp = GetTemplateChild("PART_ContentPresenter" ) as ContentPresenter; | |
if(sections.Count >0){ | |
cp.Content = sections[0]; | |
} | |
} | |
} |
Horizontal Stackpanel in WPF
Stackpanel is a useful layout control in WPF. If you have a set of elements need to sit side by side each other, this is your best option. For example, in my advgen contact manager, in the right hand side, there is a set of buttons. Thus, I placed a stack panel. However, by the default, the controls inside the panel will flow in vertical direct, you need to set Orientation="Horizontal"
E.g.
<StackPanel FlowDirection="LeftToRight" Orientation="Horizontal">
Styles in WPF
I have some styling in my WPF opensource project, AdvGen Contact Manager. That is similar with css, just state the class name like :
<Grid
Grid.Column="1"
Name="ContentPanel"
Style="{StaticResource BluePanel}">
Creating my first MVC5 Project
In the old time, we choose the MVC project templates to create a new project.
In the Visual Studio 2013, The workflow to create a new MVC5 project is different from the old versions. It changed the concept, MVC is a type of web application. So, we select File -> New -> Project ....
Defining Styles in WPF
Of course, we can put the styles for controls in each windows xaml file. But I am more prefer to all styles storing in a single file, that is more similar with CSS file. If any changes in styles required, you need to modify a single file. That is more manageable.
But, please don't forget to add the reference in App.xaml:
<Application.Resources>
<ResourceDictionary Source=
"Styles.xaml"
/>
</Application.Resources>
For further details please visit our opensource project - AdvGenContact Manager