简体   繁体   中英

Best practice for closing tags in WPF

I am currently reading the book Pro WPF in C# 2008 , and I'm a newbie to WPF.

I basically have a questions regarding best practice, as I want to write code that is commonly accepted by other developers.

I see throughout the book, that the author uses different ways of closing tags for different purposes. I'll give an example:

When creating a grid, and defining the rows and columns, he always write this code similar to this:

<Grid.ColumnDefinitions>
  <ColumnDefinition />
  <ColumnDefinition />
</Grid.ColumnDefinitions>

So he closes the tag "inline" inside the tag since the tag does not have any content (I'm not sure if inline is the correct wording for this)

But most other places, he will put a closing tag, even if it's no content like this

<TextBlock Text="{Binding Path=CategoryName}"></TextBlock>

I also see, that if he defines any attributes in the ColumnDefinition case he will also add the closing tag like this

<ColumnDefinition Width="Auto"></ColumnDefinition>

My question is simply. Are there any reason to write it like this? I think it looks more tidy to omit the closing tag is there is no contents in all cases.

So is this just a matter of personal preference, or are there any other reasons to switch between the two.

It's personal preference as the code is equivalent.

However, I can see that

<TextBlock Text="{Binding Path=CategoryName}"></TextBlock>

will come about if the line is originally written as:

<TextBlock Text="{Binding Path=CategoryName}">
    some other xaml
</TextBlock>

but then the "other xaml" is removed (for whatever reason)

What you should do is come up with a standard and stick to it (which ever way you decide to go).

This is more of an XML thing than a WPF thing and mostly doesn't matter since they just parse the XML. In general though I'd recommend always to use "Empty elements" (<tag/>) when you don't have any child elements since it both looks cleaner and prevents any accidental whitespace in the contents of the tag.

He's probably just inconsistent in the book by accident

When adding a control that has no elements inside it, better to close it by self-closing tag “/>” instead of the hard closing tag .

eg.

<Label> 
    <Label.Content> 
        <TextBlock> 
            Test! 
        </TextBlock> 
    </Label.Content> 
</Label> 


<TextBlock Text={Binding Name}/>

In my opinion it is more of a personal taste. But having said that, there are some scenarios where you are forced to use notation like <keyword></keyword> . So, unless forced there are no reasons why you should write in one way or the other. I am adding this question to my favorite list to see if there is any special guideline.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM