Unkeyed DataTemplate Resolution Issue

Hello Everyone!

So recently i have been playing around with dynamically injecting a ResourceDictionary that contains an Unkeyed DataTemplate into the Resource Lookup Tree before the Generic.xaml that contains the default DataTemplate targetting the same type.  One would think that if a loaded ContentControl whose Content is an instance of an object that is the same type as the DataTemplate that the UI would find the newly resolved DataTemplate and switch the UI.  I have found that this does not work.  You can do the same thing with a Style and it will properly flip the UI to the definition of the newly injected Style, but not for a DataTemplate.

So the question becomes, how can we provide this setup?  What im going to do today is show you how you can setup your ContentControl to support this functionality!

So the first thing we are going to do is go ahead and give our DataTemplate a Key.

<DataTemplate DataType="{x:Type ssVms:SlideShowViewModel}"
              x:Key="SlideShowViewModelDataTemplate">

Next we are going to bind our ContentControls ContentTemplate property as a “Dynamic” resource as such.

<ContentControl x:Name="SlideShowViewModelHost"
                ContentTemplate="{DynamicResource SlideShowViewModelDataTemplate}"/>

Now the DynamicResource is the key here.  Becuase it is explicitly set as a DynamicResource it causes more evaluation of found resources causing it to be invalidated when you inject a new ResourceDictionary.  Now that we have this we can swap out ResourceDictionaries containing new DataTemplates for our objects and have the UI automatically flip to the new visuals!

Hope this helps anyone else running into this same issue.  Have a good day!

No Comments

Attended Sharepoint Saturday

Hello All!

Last saturday I attended the Sharepoing Saturday conference and it was a blast!

First of all, a big thanks to Dan Attis for setting up and organizing the event, he did a great job!

So I have never actually looked into anything Sharepoint before and wanted to go to this event because I thought it would be a great way to start off.  A good portion of the topics were a good bit advanced (at least to someone new to Sharepoint :) ) so i had some difficulty finding the right sessions to go to but I think the ones i did find were very helpful.

The first session i went to was done by Phil Wicklund and was titled – Development: Building the next Generation of SharePoint Web Parts – how to Leverage JQuery and Silverlight!  In this session we learned how we can include the wildly popular JQuery and Silverlight in our Sharepoint Applications.  I have to say that after seeing this session, I can see a good adoption of both of these technologies into Sharepoint and they will end up becoming key to making very cool Sharepoint applications.  Most of the content was around JQuery and Silverlight itself, but the ease of integration with Sharepoint is the kicker.

I decided to skip out on the second session because all of the topics seemed a bit beyond where i was willing to venture for the moment.  So instead i went out to the common area for the speakers to see if i could have a one on one talk with one of them about getting started with Sharepoint.  I had a great conversation with Michael Lotter about things like key terms to understand, what books and articles would be good to start off with and a general discussion of just the base object model used in Sharepoint.

The third session (but my second) was the one i had been waiting for all day.  The session was Development: Getting started with SharePoint Development by Aaron Cutlip.  In this session we got our first basic dive into some of the beginning end user and development concepts in Sharepoint.  This is a session that can be hard at times because their are many different starting points in Sharepoint and each starting point could cover its own entire day of content to really get an introduction.  With the time frame given i was very impressed with the presentation Aaron gave.  I came out of there understanding a whole lot more about Sharepoint and where i needed to start.

The fourth session (but my third) that i attended was Development: Building Custom List Forms in ASP.NET by Doug Ware.  Doug is a local Sharepoint guy here in Atlanta and is always great to watch doing a presentation.  This topic went over the different ways that a Sharepoint List Form can be customized to reach a large range of goals that it can provide.  This was a more advanced topic and i was only half-confused by him.  He did a great job presenting and relaying the information, i just think i might not have been ready to take all of that information in :)

The last session i decided to skip because I think i had enough information for the day and the rest all seemed like topics i might not understand do much.  So instead i went over to the popular Rock Band setup and tried my best at laying down some riffs and doing some singing with the other people that attended.  I had never played Rock Band before so it was alot of fun for me.

Afterwards we had the closing ceremonies and awards.  They pulled random names for receiving a book as an award and it turned out that they had enough books for every single person to get one.  I personally got one on using Silverlight in Sharepoing :) .  I figured it would be a good match for my WPF/Silverlight specialty.

Lastly but always a blast was the Sharepint meetup at Millers Ale House after the conference.  This is where everyone gets together for some food and drinks afterwards and any furthur discussions.  Always fun to go to these.

Well thats about it for Sharepoint Saturday.  Again a big thanks to Dan Attis for setting all of this up.  And also a thanks to all the sponsers that made this happen.

No Comments

WPF DataTemplates

Hello again All!

Today im going to talk a little on how to use a DataTemplate in WPF.  Many people new to WPF generally run across the need to use a ItemsControl, ListBox, or ListView for their repeating item data.  Usually the first thing they find is that they have to set the ItemTemplate property which uses a DataTemplate to provide how each item should be visually represented.  I find that this is generally the extent of knowledge that people new to WPF have on DataTemplate.  This blog is going to go a bit more in depth into what a DataTemplate is and to show other ways we can use them!

So first lets actually define what a DataTemplate is.  A DataTemplate is a visual template that is a representation of data!  Wow were really into some deep logic here :) .  A DataTemplate directly relates to the concept of Content when using any form of a ContentControl.  To see more information of the WPF ContentControl Content model please see Controls Content Model Overview. When you apply a DataTemplate you are applying the Template to the Content directly.  When we think about what we can do with a DataTemplate we find there are different ways in which we can specify what data we want to template.

First lets go over an ItemsControl example.

When we look at the ItemsControl we have a property called ItemTemplate.  This property receives a DataTemplate.  Lets say we have a list of Person objects and we want to display LastName, FirstName.  This is how we could represent that in code.

<ItemsControl ItemsSource="{StaticResource MyPersonsList}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding LastName}"/>
                <TextBlock Text=", "/>
                <TextBlock Text="{Binding FirstName}"/>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Notice that our DataTemplate contains a horizontal StackPanel and the TextBlocks are arranged in a way that will show something like Doe, John for that entry in the Person list.  We have also not specified any attributes in the DataTemplate.  The reason this works is because control inheriting from ItemsControl automatically knows to go ahead and force the association of the template with the Content of each item in the ItemsControl.  Each item that is generated hosts a Content property which the template is applied to as stated above in defining a DataTemplate.

Before we move on to more complex concepts I’ll show how we can also use this concept in just a standard ContentControl.

<ContentControl Content="{StaticResource MySinglePerson}">
    <ContentControl.ContentTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding LastName}"/>
                <TextBlock Text=", "/>
                <TextBlock Text="{Binding FirstName}"/>
            </StackPanel>
        </DataTemplate>
    </ContentControl.ContentTemplate>
</ContentControl>

As you can see here we have specified the ContentTemplate property to display content for this control in the same way that we did in the ItemsControl.  This again shows the relation to the Content model in WPF where we saying that we want whatever content is set to the control to be displayed in a certain way.

Now that we have seen how to use a DataTemplate we have noticed that we have used the same DataTemplate for two different controls.  Well we definatly do not want to duplicate this everywhere in the application that has the Person object formatted in the same way.  Luckilly for us we can put DataTemplates as keyed resources!

Lets say that we have many different screens that all need to make use of this same data format.  What we can do is go into our App.xaml and add this template with a key to its resource collection.  (Note*  When WPF looks for a resource the App.xaml is the second to last place it checks when finding the resource.  This ensures that all of our screens in this project will be able to find the DataTemplate correctly).  Our App.xaml may look something like this.

<Application x:Class="DataTemplateExample.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="Window1.xaml">
    <Application.Resources>
        <DataTemplate x:Key="PersonNameDataTemplate">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding LastName}"/>
                <TextBlock Text=", "/>
                <TextBlock Text="{Binding FirstName}"/>
            </StackPanel>
        </DataTemplate>
    </Application.Resources>
</Application>

What we have done is said that we want to expose a DataTemplate to the entire application called PersonNameDataTemplate to use as we wish.  Now if we modify our ItemsControl and ContentControl code to use this template it would now look like this.

<ItemsControl ItemsSource="{StaticResource MyPersonList}"
              ItemTemplate="{StaticResource PersonNameDataTemplate}"/>

<ContentControl Content="{StaticResource MySinglePerson}"
                ContentTemplate="{StaticResource PersonNameDataTemplate}"/>

Now we have managed to reuse a common template with only having to specify it once!  We can reference this template anywhere we know we are setting Person objects as content to all be displayed in the exact same way.

Now lets go a final step and see how we can automatically have a DataTemplate applied without even needing to reference the template itself!  Imagine that we automatically know that everywhere in the application where we are using a Person object as content that it should all be displayed this same way.  This is not a real-case scenario as there will probably not be any application where all Person objects only show the name in this format.  But their are many cases where we would want to say that one object type should always be represented in the same way.  And this is what im going to talk about  next.

So for humors sake we want all Person objects to be displayed as LastName, FirstName in the entire application.  The way we do this is by not specifying a key and instead specifying a specific data type.  We still want to put the DataTemplate in the App.xaml Resources collection so that the entire app can automatically find the template when applicable.  The code should now look something like this.

<Application x:Class="DataTemplateExample.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:models="clr-namespace:DataTemplateExample.Models"
    StartupUri="Window1.xaml">
    <Application.Resources>
        <DataTemplate DataType="{x:Type models:Person}">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding LastName}"/>
                <TextBlock Text=", "/>
                <TextBlock Text="{Binding FirstName}"/>
            </StackPanel>
        </DataTemplate>
    </Application.Resources>
</Application>

We have added a namespace delcaration pointing to where we are storing our models so that we can get to the person type.  As you can see i have removed the key and instead added DataType=”{x:Type models:Person}”.  What this does is says that anytime in the entire application where an object of type Person is set as content that this DataTemplate should be used.  This is known as a global un-keyed template.  Unkeyed DataTemplates that specify a DataType will always be used when that type is set to Content.

Now that we have our global un-keyed DataTemplate this is how our ItemsControl and ContentControl would now look.

<ItemsControl ItemsSource="{StaticResource MyPersonList}"/>

<ContentControl Content="{StaticResource MySinglePerson}"/>

We have not specified any templates to be used, but the global template we have defined will automatically be used!  This is a very powerful technique that can be used accross many different aspects of WPF development. 

Lets say we wanted Themeing and in another Theme we wanted to always show FirstName, LastName.  Well we could create a second un-keyed DataTemplate and at runtime inject the new one into the Resource Tree lookup before our default and our UI will automatically change to reflect the new template!  Imagine this on a grand scale of being able to build complete lookless, themeable applications!  For more information on how the Resource lookups and Trees work please see Trees in WPF.

Global DataTemplates can also be a key player in the popular MVVM patthern for WPF.  You can create a DataTemplate representing a ViewModel so that all you have to do is create ViewModel’s and set them as content.  To see more about MVVM in WPF please see Josh Smith’s MSDN article WPF Apps With The Model-View-ViewModel Design Pattern.  Read the entire article and all code samples and you will find the DataTemplate relevance to this pattern.

Well i hope you all have enjoyed this article and learned something from it and hope you have a happy coding day!

3 Comments

Vegas Vacation

Hello All!  Time for a non-technical blog.

Last week me and my wife went on vacation to Las Vegas for the first time and wow was it alot of fun.  We got to see many shows, see the Grand Canyon, ate alot of food and got some nice relaxation in.

Our first show we saw was Danny Gans at the Encore/Wynn.  Hands-down the best show i have ever seen.  He is a true one-man variety show.  He does over 200 impersonations, sings, dances, plays instruments, does stand-up comedy and much more.  If anyone is ever in Las Vegas i would definatly recommend going to see him.

The second show we saw was KA at the MGM Grand.  This is a Cirque du Soleil show with a good kinda samurai setting.  The story is one many of us have seen but the way KA presents it is phenomenal.  There is a heavy emphasis on swordplay shown by very skilled actors.  There is definatly some really cool strangeness when you see creatures the size of humans moving around with precise style.  There were 2 very good displays of acrobatics.  I would definatly recommend seeing this show or other Cirque du Soleil shows while in Vegas.

There are other Cirque shows that were recommended that we did not get to see.  O is a heavy water based show that is supposed to be very good.  Another is Love.  This one is a Beatles themed Cirque du Soleil that has had raving reviews by both tourists and locals.

We also took a helicopter tour of the Grand Canyon.  Ive seen many pictures of the Grand Canyon but none of them do it justice.  You really have to be there to take in the wonder that it is.  The tour included flying through the canyon and landing for a half an hour for snacks and champagne and also provides good picture opportunities.

We got to stay at the Bellagio and man is it a nice hotel.  It covers a city block by itself and has many restaurants and shopping venues without ever having to leave the building.  Right now is a very good time for hotel prices.  The Bellagio is in the top 5 in Vegas and we got our room for about 150$ a night.  This is unheard of by people who have been to Vegas in the past.

Having never been to Vegas before i wasnt really sure what to expect.  Now that i have been i would definatly go back and recommend anyone seeking a fun vacation to check it out.  If you are looking for a relaxing vacation i would not recommend it.  While we did get some relaxation in, its a place that when you come home you are absolutely exhausted.

Well thats it for my vacation rant and more technical blogs on WPF are soon to come, so stay tuned!

No Comments

How to Create a Custom Dependency Property

Hello Everyone!

Today I’m going to talk about how to create a Custom Dependency Property for use within WPF.  When used with creating custom controls they can be used to extend the functionality of the control.  They can be used for many other reasons but for now we are going to stick within the context of using them for a control.

Lets say were going to build a sort of Watermark text functionality into a TextBox control.  This will allow a developer to specify a string of light gray text that should be shown when no text is present and the control doesnt have any form of focus.  Well the first thing we will need is a custom property on the TextBox control to store this text in.  This is the perfect place to use a DependencyProperty.

First lets create our class.

public class WatermarkedTextBox : TextBox
{
    static WatermarkedTextBox()
    {

        DefaultStyleKeyProperty.OverrideMetadata(typeof(WatermarkedTextBox),
new FrameworkPropertyMetadata(typeof(WatermarkedTextBox)));
    }
}

Next were going to use yet another wonder snippet provided by Visual Studio called propdp.

If we type in propdp and hit tab twice we will see this appear.

public int MyProperty
{
    get { return (int)GetValue(MyPropertyProperty); }
    set { SetValue(MyPropertyProperty, value); }
}

public static readonly DependencyProperty MyPropertyProperty =
    DependencyProperty.Register("MyProperty", typeof(int), typeof(ownerclass), new UIPropertyMetadata(0));

This should be very familiar from my previous blog on WPF Attached Properties.  We are going to tab through and the the property type to string, the property name to WatermarkText, the ownerclass to WatermarkedTextBox, and the default value to string.empty.

Our property should now look like so

public string WatermarkText
{
    get { return (string)GetValue(WatermarkTextProperty); }
    set { SetValue(WatermarkTextProperty, value); }
}

public static readonly DependencyProperty WatermarkTextProperty =

    DependencyProperty.Register("WatermarkText", typeof(string), typeof(WatermarkedTextBox),
new UIPropertyMetadata(string.Empty));

And that is it!  We now have ourselves a custom dependency property that we can use to store the text intended for the watermark functionality.  Now we can use things like TemplateBinding inside of our templates for this control to bind an elements Text or Content property to this.  This could be a label, maybe an adorner, there are many ways this can be used.  And because its a DependencyProperty we can take full advantage of what WPF provides like the Binding system, setting from Styles and if the return type were one that is animateable like double then we could also animate it.

There are a few things to note about creating a DependencyProperty.  Sometimes people like to put logic into property setters for functionality when that property has changed.  When we use a DependencyProperty the setter of the actual property that wraps the call to SetValue, does not always get called.  If something changes the property in the dependency system behind the scenes then your code is never run.

Luckilly we have a nice solution for this!  There are two different ways we can still provide this functionality.

The first way we can do this is by applying a delegate to be a PropertyChanged handler for the dependency property.  We have another constructor parameter in the UIPropertyMetadata object that will accept this delegate.  When we apply it, it should appear as shown.

public string WatermarkText
{
    get { return (string)GetValue(WatermarkTextProperty); }
    set { SetValue(WatermarkTextProperty, value); }
}

public static readonly DependencyProperty WatermarkTextProperty =

    DependencyProperty.Register("WatermarkText", typeof(string), typeof(WatermarkedTextBox),

                                 new UIPropertyMetadata(string.Empty, OnWatermarkTextChanged));



public static void OnWatermarkTextChanged(DependencyObject box, DependencyPropertyChangedEventArgs e)
{
     //Add changed functionality here
}

The second way to do this is by overriding OnPropertyChanged.  Any class that inherits from DependencyObject will automatically have this override available to them.  This method accepts DependencyPropertyChangedEventArgs e that will provide us the property that has changed, the new value, and the old value.  This is one way we might implement this.

protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
    base.OnPropertyChanged(e);

    if (e.Property == WatermarkedTextBox.WatermarkTextProperty)
    {
        //add changed functionality here
    }
}

There are many other things we can do with a DependencyProperty and to get more information please check out the MSDN page on How to: Implement a Dependency Property.

I hope this article helps and have a good day!

No Comments

What would YOU like read about!

Good Morning Everyone!

So i have started my WPF blog and have a post on Attached Properties while also providing the beginnings of a Field-Level security mechanism.  I have many many other ideas for WPF topics I want to post about, but I also want to hear what YOU, the most important person to me, wants to read about!

Send me an email at jasonr@magenic.com or post a comment on this post to submit an idea for a WPF topics and i will see if I can choose a few and start building something for them.

And as always!! Happy Coding :)

No Comments

WPF Attached Properties with Field Level Security Example

Hello Everyone!

So today I’m going to be showing you how to use WPF Attached Properties and show how we can make the beginnings of providing Field-Level security features that can be set on any provided or custom WPF control.

So: What is an Attached Property?.  An Attached Property is a property that makes use of the Dependency system to “attach” a property and a value to an instance of a DependencyObject.  What this means is that the object itself does not have the property compiled into itself, but instead the dependency system will store the object and the related attached property value.  So when you go to retrieve or set the value of the Attached Property you will pass in the instance of the object you want to set or retrieve from and it will check the dependency system if this instance has a value (when retrieving) or it will register the value, object, and property name into the dependency system.  This allows us to assign values to properties that do not actually exist on the DependencyObject.

So let’s now create our first Attached Property and see how we can use it to create the beginnings of a Field-Level security mechanism!

First create a class called ApplicationSecurity.  This class can be static or instance, but must be public if intended to be used from the outside.

Luckily Visual Studio 2008 (I have not tried in previous versions of Visual Studio) already has a snippet for us to simply create the shell of the an Attached Property.  This snippet is called propa.  So if we type propa then tab twice it will create the code you will se below.

public static int GetMyProperty(DependencyObject obj)
{
       return (int)obj.GetValue(MyPropertyProperty);
}

public static void SetMyProperty(DependencyObject obj, int value)
{
       obj.SetValue(MyPropertyProperty, value);
}


public static readonly DependencyProperty MyPropertyProperty =

      DependencyProperty.RegisterAttached("MyProperty", typeof(int), typeof(ownerclass),
new UIPropertyMetadata(0));

There are 4 green placeholders for modifying the default information of the snippet to really create our Attached Property.  The first placeholder will what Type you expect the Dependency property to be.  Since we are working towards Field-Level security we are going to go ahead and make it of type string.  So type string into the first area then hit tab.  You will see it also modifies other parts of the snippet in order to propogate the correct type that it needs. 

The second green placeholder is the name of our property.  When thinking of providing field level security we might want to go about a way of defining a unique field context name for our field.  So if you image you have a screen control called PersonView and it contains a FirstName field you might want to assign that field PersonViewFirstName to provide a unique identifier for this field.  So for this part of the snippet we will type in FieldContextName and hit tab.  Again you will see that it will modify other parts of the snippet in order to maintain what it needs.

The third green placeholder is the owner type.  This will generally be the type of class you put the property in.  So since we are in a class called ApplicationSecurity we would type in ApplicationSecurity.  The placeholder is already in the typeof declaration so no need to include that.

The fourth green placeholder is the default value contained inside the UIPropertyMetadata parameter.  If your property return type is a reference type (object) then you must set this to null.  If you set this to a new instance of the object that same instance will be the default for all references to the property across all objects.  This can get messy so we will just set it to null.  If its a value type you can set it to the intended default.  Since we are making a string property we will type in string.Empty and hit enter. 

This ends the creation of our snippet and our Attached Property and here is what you end up with.

public static string GetFieldContextName(DependencyObject obj)
{
    return (string)obj.GetValue(FieldContextNameProperty);
}

public static void SetFieldContextName(DependencyObject obj, string value)
{
    obj.SetValue(FieldContextNameProperty, value);
}

public static readonly DependencyProperty FieldContextNameProperty =

         DependencyProperty.RegisterAttached("FieldContextName", typeof(string),

                typeof(ApplicationSecurity), new UIPropertyMetadata(string.Empty));



We now have an Attached Property called FieldContextName that we can use to assign a value to any DependencyObject with this property name.  This is how you would use it in XAML.

<TextBox appSec:ApplicationSecurity.FieldContextName="PersonViewFirstName" />

When this instance of the TextBox is created it will automatically register this property with this TextBox and the value into the Dependency System.  If you wanted to manually manually work with this from code-behind (which is mostly the same as what happens automatically when done from XAML) this is how you would do this.

TextBox myTextBox = new TextBox();
ApplicationSecurity.SetFieldContextName(myTextBox, "PersonViewFirstName");

string fieldContextName = ApplicationSecurity.GetFieldContextName(myTextBox);

So that is the basics of how to use Attached Properties.  But now lets look at how we can slightly extend this functionality so that when the control is created (or the property is set from code behind) it will evaluate what its security level should be.

In the UIPropertyMetadata object added as a parameter to the registration of the Attached Property we have a few more overloaded parameters that we can add.  The second parameter (after setting the default value) accepts a PropertyChangedCallback object whose constructor accepts a static delegate that is called when the value changes. You can also just put the delegate directly as the parameter instead of creating the PropertyChangedCallback object.  Here is how our property looks now.

public static string GetFieldContextName(DependencyObject obj)
{
    return (string)obj.GetValue(FieldContextNameProperty);
}

public static void SetFieldContextName(DependencyObject obj, string value)
{
    obj.SetValue(FieldContextNameProperty, value);
}

public static readonly DependencyProperty FieldContextNameProperty =

   DependencyProperty.RegisterAttached("FieldContextName", typeof(string), typeof(ApplicationSecurity),
new UIPropertyMetadata(string.Empty, OnFieldContextNameChanged));

So now lets take a look at that method.

private static void OnFieldContextNameChanged(DependencyObject, obj, DependencyPropertyChangedEventArgs e)
{
     //ApplicationSecurityManager.EvaluateField(obj, e.NewValue);
}

So what will happen now is anytime the FieldContextName is set onto a Dependency object whether through XAML or code-behind this method will be called.  The obj parameter is the DependencyObject that this property was set on, and the e parameter will contain OldValue and NewValue.  So you see that if we use this on a WPF control at this point we could pass the context that this field belongs to, to evaluate what needs to happen to the control, and since you have the control also its already available so that you can make any modifications based on security (ie.  Set Visibility to Collapsed because the current user doesnt have access to this field).

I hope people enjoy this comment and please feel free to leave comments, suggestions, criticisms.

1 Comment

My First Blog

Hello Everyone!

My name is Jason Rainwater and i am a Consultant for Magenic Technologies.  Friends and colleagues have been suggesting I start a blog to share with everyone the knowledge of Microsoft’s WPF Framework, so here I am!

I hope to be covering many aspects, concepts, usage and practices for WPF and hope most of that people benefit from what I know.  I will never admit to knowing everything about WPF and always welcome suggestions and comments on topics I write about.

I hope you all will enjoy what I have to share and stay tuned for the real content to come!

No Comments