Pages

Tuesday 3 June 2014

WPF XAML: Property-Attribute and Property-Element Syntax for Simple and Complex Properties

WPF XAML: Property-Attribute and Property-Element Syntax for Simple and Complex Properties

Property-Attribute and Property-Element are the two approaches in WPF XAML to set the properties of the elements. I will take a very simple example to clear the concepts of both of the Property-Attribute and Property-Element approaches. Lets try to set the background property of the grid. I want to fill the background of the grid with some gradient color. Lets see how can we do this using XAML in WPF?

Suppose I have to set the background of the grid to Green. I will set it like this:

<Grid Name="MyGrid" Background="Green">
....
....
</Grid>

In the above case, I have used Property-Attribute syntax for setting the Background property. WPF has used default brush and painted the area with solid color. But what if you want to use some complex brush and want to paint the background with gradients instead of simple solid color? 

In this scenario, you will have to use Property-Element syntax defined in WPF XAML. Property-Element syntax is represented as ElementName.PropertyName. For example, you have to use Background property in this case as Grid.Background.

So, to introduce gradients in my example, I will have to use LinearGradientBrush instead of the default brush used by WPF for solid fill.

<Grid Name="MyGrid">
  <Grid.Background>
    <LinearGradientBrush>
     <LinearGradientBrush.GradientStops>
       <GradientStop Offset="0.00" Color="Red" />
<GradientStop Offset="0.50" Color="Indigo" />
<GradientStop Offset="1.00" Color="Violet" />
     </LinearGradientBrush.GradientStops>
</LinearGradientBrush>
  </Grid.Background>
</Grid>

In the above example, I have chosen different gradient colors (Red, Indigo and Violet) to paint the background of the Grid.

With this, I think I have cleared the concept of Property-Attribute and Property-Element syntax used in WPF XAML.

No comments:

Post a Comment

About the Author

I have more than 10 years of experience in IT industry. Linkedin Profile

I am currently messing up with neural networks in deep learning. I am learning Python, TensorFlow and Keras.

Author: I am an author of a book on deep learning.

Quiz: I run an online quiz on machine learning and deep learning.