Amend Optional Attribute Names in XAML
Polishing some XAML
Published: April 12th, 2020
I have to admit I am a stickler for detail. Ok, a lot of developers are born this way, but this post discloses a certain degree most of the developers I know miss. Here comes a procedure to enrich your XAML with optional attribute names, e.g. the word Path
.
The XAML compiler gets along with binding expressions missing the Path
attribute name, resource references missing the ResourceKey
attribute name, and static references missing the Member
attribute name. The code editor gets along as well, but fails to color the attribute values appropriately. The following code snippets show the difference. They would not naturally occur in the same code file, but are here assembled exemplarily.
<TextBlock Text="{Binding Name}" Foreground="{DynamicResource SuperSoftware.Brushes.StandardTextForeground}" /> <TextBlock Text="{x:Static localization:MainResource.TextKey}" /> <Border BorderBrush="{TemplateBinding BorderBrush}" /> |
<TextBlock Text="{Binding Path=Name}" Foreground="{DynamicResource ResourceKey=SuperSoftware.Brushes.StandardTextForeground}" /> <TextBlock Text="{x:Static Member=localization:MainResource.TextKey}" /> <Border BorderBrush="{TemplateBinding Property=BorderBrush}" /> |
It is quite easy to adjust this. A simple Find-&-Replace using the following regular expressions does the job.
Attribute Name | RegEx in Find | Expression in Replace |
---|---|---|
Path |
(\{Binding\s+)(?!(Path=|Converter(Parameter)?=|RelativeSource=|Mode=|ElementName=|FallbackValue=|Source=|\})) |
$1Path= |
ResourceKey |
\{((Static|Dynamic)Resource\s+)(?!ResourceKey=) |
{$1ResourceKey= |
Member |
(\{x:Static\s+)(?!Member=) |
$1Member= |
Property |
(\{TemplateBinding\s+)(?!(Property=|Converter(Parameter)?=|\})) |
$1Property= |
Be careful. If you apply these to a typical middle aged project you will likely have a lot of code changes leaving a fissure in its change log. You have to decide whether it is worth the effort.