Monday, May 2, 2011

WPF Dependency Property Validation and Coercion

Hey guys! Welcome to WPF Tutorials, today we will be continuing our talk on Dependency Properties.

Link to List of Precedence Order:

Transscript from Tutorial:
Last time we created a simple IsPurple boolean dependency property and implement the PropertyChangedCallback. Today I want to talk about property validation, coercion, and value precedence.

Now to illustrate property validation I want to quickly create a simple TextBlock control that has 2 properties:
1) A NumberValue property that can only be numeric.
2) A ForceInteger value that if set to true will coerce the NumberValue to an integer.

So for this we need to create two dependency properties under a new class called
MyTextBlock, which inherits TextBlock.

Since we’ve already shown last time what a Dependency Property looks like and how to create one. I am just going to use the snippets this time.

Let’s get going with the NumberValue property of type String which HAS to contain a numeric value.

So we’ll just call this NumberValue which will be of type string, and have a default value of “0”

Then all we have to do is implement the validateValueCallback method IsValidNumber, which only expects a parameter of type Object.

Now that we have IsValidNumber implemented we can pass the AddressOf IsValidNumber to the
validateValueCallback so the property system can call it when it is ready.

Now,check out what happens when we go to our XAML view and try to set NumberValue to something that isn’t a number. The xaml engine actually knows that the value we gave it doesn’t pass the IsValidNumber test and the application actually won’t even compile. This is really cool.

Next we are going to talk about Property Coercion which is basically a property system feature that prevents values from getting out of sync or containing invalid data

But before going into coercion I want to talk real quick about value precedence. This is a really interesting concept.

So, when a dependency property gets set by us through the xaml or code-behind that value is called the local value. The local value is actually only the 3rd place that the property system looks to resolve the property’s effective value.

The first place the property system looks to find that effective value happens to be the result of a coercion. Then it checks to see if the value has been changed by an animation. Then it continues on to use the local value.

I’ll post a link below the video, so you can see what other locations the property system looks to find an active value.

So let’s get back to the task at hand:
Let’s complete the coersion method for the NumberValue property. For now the only thing we need to check is if the value is a decimal if it is we’ll just round up to the nearest integer otherwise we’ll return the value that was passed in.

Next we’ll go ahead and create the ForceInteger property.

So if the force integer value gets set to true we want to coerce the NumberValueProperty.
Since forceInteger’s value is defaulted to false, we need some way of detecting if the property has been changed. In normal CLR properties it would have been safe to put the custom logic in the ForceInteger’s setter, since we are using DPs it’s not safe to do that because SetValue CAN be called directly and if that were the case then any code in the Set of the property would never be called.

So instead of putting the code inside of the setter, we have the PropertyChanged callback which is part of the PropertyMetaData Object. The PropertyChanged callback method expects two parameters the DependencyObject and the DPChangedEventArgs.

So for our ForceIntegerPropertyChanged callback method, we just need to check if ForceInteger is being set to True, if so then Coerce the value of the NumberValueProperty.

So to test this out, I set up a form that has a force integer checkbox and a get number value button.

Tuesday, April 26, 2011

WPF Dependency Properties Intro

Hey guys!! For today's WPF Tutorial, we are going to talk about Dependency Properties in WPF!

CLR Properties
The best way to get through this Dependency Property discussion is to take a step back and first talk about CLR Properties. CLR properties usually consist of a private variable and getters and/or setters which set the value of the private variable.

So first we are going to create a custom StackPanel with a simple CLR IsPurple property on it that will change the background color of the stack panel to purple if we set it to true.

*Show a simple CLR IsPurple property*

One drawback of CLR Properties is that they are taking up memory in the application whether they ever get changed from their default values or not. Some controls and objects specify over 50 properties, many of which I know I have never changed from the default values.

So this brings us to DPs:

Introduce Dependency Properties
Dependency Properties are only actually created when used, which means that if a Button has over 100 properties only the dependency properties that are changed from their default meta data values actually use up memory.

So let’s get right into what a DP definition looks like:

For the first example I want to simply show how we can re-create the IsPurple property as a dependency property

So let’s insert the dependency proeprty snippet.


EHHH! If you are anything like me, this and this look pretty much the same.

So, what I have found is things make a LOT more sense when I break them down and go through them step by step. So let’s do that real quick.

We are going to create our first dependency property from scratch.

So, the first thing you’ll notice is that the Dependency Property definition is shared...
So why is that? What we are doing is only defining the property as opposed to using up memory by actually creating the property and storing its value. This way the DP is defined only once and not each time a new instance of the object is created thus using up less memory along the way.

The next thing you’ll notice, is that the we are declaring the dependency property with the name
IsPurpleProperty, declaring the DP name by ending it in ‘Property’ is a standard convention in .NET to maintain consistency.

So now we want to Register the actual DP.
First, we’ll give it the name that the users of the property will refer to it: which is IsPurple
next, we’ll give it the type the property expects to get and return.
then, we’ll give it the type of the owner or basically the name of the class you will be using the property on: which is MyStackPanel.

now, register expects a parameter of type PropertyMetaData, in which case we’ll give it a new instance of FrameworkPropertyMetadata and you’ll notice here that there are a lot of different overloads for this object. We are going to use one of the simpler ones first, where we give it just a default value of “false”.

Now we need to have a way to access the dependency property for this we have a Property Wrapper, this allows our dependency property to be used as if it were just a plain property. So let’s call this “IsPurple”.

So let’s run this and see what happens.

So you’ll notice that nothing happens when we change the IsPurple property value to true.

What we need to do here is define something called a PropertyChangedCallback. All that we are doing here is defining a method named IsPurplePropertyChanged that gets called when the value gets changed.

The callback is expected to have two parameters: one of type dependencyObject and another of type DependencyPropertyChangedEventArgs.

The dependency object can be cast to the object we are putting the DP on.
The eventargs can be cast to the type of the DependencyProperty.

Then we simply add our logic and set the properties that need to be set.

So then we’ll pass in the AddressOf the method to the metadata object so the DP property system can call the IsPurplePropertyChanged method when it is ready.

*Now test it out show it working. (even in the designer view...)*

So, that is actually it for today guys! Today hopefully you have a better understanding
of how to create a DP in WPF. If you have questions, comments or suggestions please leave those below the video! Don’t forget to subscribe if you haven’t already. Thanks and see you guys next time!

Saturday, April 9, 2011

WPF ViewBox

For today's WPF Tutorial, we are going to be talking about the WPF ViewBox!

Transcript from Video:
So basically what the ViewBox is, is another WPF decorator. It allows any content that goes into it to be sized to fit the ViewBox’s bounds.

So normally, when we put a textblock in a button, we get something like this. The button automatically re-sizes with the size of the cell, but the textblock in the button stays the same size and this just feels and looks weird... so what we can do to illustrate what the viewbox does is put the viewbox in a button and the textblock in the viewbox. Now as the button re-sizes the TextBlock does as well.

There are a couple of key properties I want you guys to be aware of when using the viewbox.
The StretchDirection property and the Stretch property:
To illustrate these properties we have a 900px x 900px image inside of a viewbox.
These 4 buttons up top will set the Stretch property and the 3 butons and the bottom
will set the StretchDirection properties.

1) The StretchDirection Property can be one of 3 values
“UpOnly” : The content (the image in this case) will allow the content to get bigger but won’t get smaller than it’s orginal size.
“DownOnly” : This allows the the content to get smaller but not get bigger.
“Both” : The content stretches to fit the parent according to the Stretch Property. This is the default property of the ViewBox.

2) The Stretch Property can be one of 4 values
“None” : The content keeps its original size
“Fill” : The content is resized to fit the ViewBox dimensions.Th aspect ratio will NOT be preserved.
“Uniform” : The content is resized to fit in the ViewBox dimensions while preserving the aspect ratio.
“UniformToFill” : The content is resized to fill the ViewBox dimensions while it preserves its native aspect ratio. If the aspect ratio of the ViewBox differs from the source, the source content is clipped to fit in the ViewBox dimensions.

So that is actually it for today guys!
I hope from today’s video you understand what the viewbox does and how the Stretch and StretchDirection properties work! As always if you have any questions comments or suggestions please leave those below the video! Don’t forget to subscribe, Thanks for watching and see you guys next time.

Wednesday, April 6, 2011

WPF Borders

Hey guys! Welcome to another WPF Tutorial! Today we are going to be talking about Borders in WPF.

So in WPF Borders are considered to be a decorator. They are used commonly with a Layout Panel. There are about 4 key properties we need to be aware of when using the Border.
1) Background - sets the background color of all the content within the border.
2) BorderBrush - allows you to set the color of the edge of the border.
3) BorderThickness - allows you to determine the thickness of the edge.
4) Corner Radius - Allows you to curve or round the corners of the border, for a nice effect.

Monday, April 4, 2011

WPF Expander

So, for today’s WPF Tutorial we are going to be talking about the Expander in WPF.

Today we are going to build on tutorial 17 where I introduce the concept of HeaderedContentControls and show you the GroupBox and TabItem.

The Expander is just another HeaderedContentControl similar to the GroupBox except it has the ability to hide it’s content by collapsing or show content by expanding. Many of you may remember this feature being used in Windows XP alot. It was called an explorer bar.

If you do a google image search, you’ll see what I mean.

Here, I have a DockPanel, with a StackPanel of Expanders docked to the left and just some plain text filling out the rest of the DockPanel.

How do we use the Expander?
It’s simple, we just put the content we want to display inside of the opening and closing expander tags. Now the content can be expanded and collapsed.

Now, notice when I run the application the Expander will initially be collapsed. But we don’t want that in this situation. So it gives us an isExpanded property that we can set to true and have it be expanded by default.

Friday, April 1, 2011

WPF GroupBox and TabItem

Hello! For today's WPF Tutorial we are going to be talking about HeaderedContentControls like GroupBox and TabItem.

What is it?
So, first of all, what’s a HeaderedContentControl?

Well, the HeaderedContentControl derives from the ContentControl which simply addsone extra feature to it...a Header. So The GroupBox happens to be one such control that derives from the HeaderedContentControl.

So as you can see here from the XAML that I have constructed. Some of you Windows users out there are gonna recognize this or kind of recognize it. It is the System Properties dialog, it is actually a bunch of GroupBoxes and I think whenever we go into My Computer-> Properties -> Change Settings.

What you may have never thought about until now is that in the System Properties window Performance, User Profiles and Startup and Recovery are each GroupBoxes. These are considered HeaderedContentControls.

So How Do We Use Them?
It’s very simple. What I did was created a StackPanel of GroupBoxes. So we just define the GroupBox as an opening and closing tag and add a header attribute and name it. Then all of your content goes in between the GroupBox tags. Now remember these are technically still content controls so you can only have one element in the GroupBox. However that one element CAN be a Layout Container, which can have multiple element in it.

Now, the header is ALSO a content Control so we aren’t just limited to using plain old boring TextBlocks. We can use the GroupBox.Header property element and I have a stackPanel here of an image and a TextBlock. We can put images in the Header of the GroupBox as well.

So on to the TabItem...
All we need to do is create a TabControl. We are going to create a TabItem and that TabItem’s header is going to be Advanced. All we have to do is paste all of the GroupBoxes into the TabItem.

Wednesday, March 30, 2011

The ScrollViewer

For today's WPF Tutorial we are going to be talking about the ScrollViewer in WPF!

Transcript from Video:

What is it?
Well, sometimes the content we want to display to the user is larger than the size of our window. So what the scrollviewer does for us is it allows the user to scroll through and see things would normally not be able to.

*run app*

We can clearly see here that my content is way bigger than the window.

How do I use it?
So how do we use the scrollviewer to fix this problem? It’s easy! You wrap it in a ScrollViewer tag. Now, the content easily scrolls up and down.

There are two different types of scrolling that the Scrollviewer supports: Physical and Logical scrolling. Physical scrolling allows the scrollviewer to scroll by a predetermined number of units: usually pixels. It’s basically what we’re doing right now.

Logical Scrolling is really cool, and would have been very useful to me a lot of times in the world of HTML, I think it’s a genius feature to put in WPF!

*So here is an example of Logical Scrolling*
*Show how to enable logical scrolling...*

So now, what you’ll notice is the ScrollViewer will scroll perfectly to the top of the next element in the StackPanel.

This type of scrolling only works if the container in the scrollviewer implements the IScrollInfo interface. The stackpanel is one such container that implements IScrollInfo.

If you want to force p.s. then set CanContentScroll to false.