WPF: when defining a control template (controltemplate), consider null attributes.

Source: Internet
Author: User

Many WPF control template definitions do not take into account the Member is null (default value), such as the headeredcontentcontrol control template defined below:

<ControltemplateTargettype="Headeredcontentcontrol">

<Dockpanel>

<BorderDockpanel. Dock="TOP"

Borderbrush="Red"Borderthickness="2"

Padding="5">

<ContentpresenterContentsource="Header"/>

</Border>

<Contentpresenter/>

</Dockpanel>

</Controltemplate>

 

Then headeredcontentcontrol is defined as follows:

<HeaderedcontentcontrolHeader="ABC">

<Button>Def</Button>

</Headeredcontentcontrol>

 

 

Not bad. If you omit the header attribute (the default value is null), the result will be:

 

The header is null at this time, while the border is still there, and the padding definition also occupies a certain amount of space.

 

Solution: When the controltemplate is defined, when the attribute is null, add a trigger to hide the corresponding control.

 

Therefore, the above controltemplate should set a name for border, and then judge whether the header is null through trigger. If it is null, change the visibility of border to collapsed. Of course, the content attribute does not need to be determined to be null, because the content attribute corresponds to the contentpresenter without any other station controls, and the contentpresenter does not occupy any controls (if the content is null ):

<ControltemplateTargettype="Headeredcontentcontrol">

<Dockpanel>

<BorderDockpanel. Dock="TOP"

Name="Border"

Borderbrush="Red"Borderthickness="2"

Padding="5">

<ContentpresenterContentsource="Header"/>

</Border>

<Contentpresenter/>

</Dockpanel>

<Controltemplate. triggers>

trigger property = " Header " value =" { x : null } " >

<SetterTargetname="Border"Property="Visibility"Value="Collapsed"/>

</Trigger>

</Controltemplate. triggers>

</Controltemplate>

 

In this case, the display is correct:

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.