WPF

Blending with Sample Data feature (Blend 4)

Posted on

Had a chance to play more with Blend 4 this week, have been eyeing on the Sample Data feature for a while but only had a chance to use it in practice now.

So imagine if you have defined the backing view model below

public class MainViewModel
{
	public MainViewModel()
	{
		// Insert code required on object creation below this point.
	}
	public IList<Person> Persons { get; set; }
}

public abstract class Person
{
	public String Name { get; set; }
	public Int32 Age { get; set; }
	public String Initials { get{ return "some initials"; } }
}

public class Male : Person
{
}

public class Female : Person
{
}

You can then open the view, on the top right panel, click on the Create Sample Data from Class option below

Choose the view model to generate the sample data, click Ok

Bam! the sample data file has been generated nicely below, and notice one thing, the read only Initials property can be “set” as well there :)


Before moving on to the next step, be sure to replace Person Type on the rows into either Male or Female.

Now, time to get into the view with the d:DataContext binding and data templates by Data Type for each Male and Female.

hhhmm… a little bit disappointing, isn’t it? all are seem to be in place, but why it’s displaying these weirds _.di12.NameSpace.Class rather than our expected data template result?
Now back to the xaml, add d:IsDesignTimeCreatable=”False” attribute on both data template elements, save, close and reopen the xaml again.

And there’s the shiny UI with some sample data in it :)

Notice that Blend sometimes doesn’t refresh the design view as soon as we make some changes on the data template (it works fine on non data template changes).
I only found that the effective way is to just close and reopen to see the changes effect, so if you’re editing something on the data template and it’s not reflecting, try to close and reopen it first :)

I found this sample data feature is very useful, how bout you?

Have also shared the sample project for grabs here.

Hope this helps :)

Advertisements

Extension over an extension for Dispatcher

Posted on

I’m working on a migration of an existing winform control in our WPF app into a new WPF shiny control ;)

Interestingly it was then breaking with the exception: The calling thread must be STA, because many UI components require this when trying to perform some action on the WPF control where it’s working fine for the existing winform version.

Turned out that this was due to the code was being invoked from a background thread through threadpool. Now it’s pretty easy to resolve this, we can use the Dispatcher property which is inherited by DispatcherObject abstract class which is the base class of WPF User Control.

 

 

 

 

 

 

 

Now the Dispatcher class itself turned out to have a DispatcherExtensions class (below) as well which accept Action type

 

 

 

 

 

 

So in order to fix the calling thread exception, we just need to have the following code.

void OnSomeRequest()
{
    if (!Dispatcher.CheckAccess())
    {
        Dispatcher.Invoke(() => OnSomeRequest());
    }
    else
    {
        someUserControl.DoSomething();
    }
}

Now if we only have 1 certain place which will perform some UI update in the code, this is okay, but imagine if you have many places in the code that you need to repeat the pattern above :p

So we can simplify the above again into below, we have reduced the code from 8 lines into just 1 line :)

void OnSomeRequest()
{
    Dispatcher.InvokeIfRequired(() => someUserControl.DoSomething());
}

The new extension over existing DispatcherExtension is simple.

using System;
using System.Windows.Threading;

namespace ExtensionTests
{
    public static class AnotherDispatcherExtensions
    {
        public static void InvokeIfRequired(this Dispatcher dispatcher, Action action)
        {
            if (!dispatcher.CheckAccess())
            {
                dispatcher.Invoke(action);
            }
            else
            {
                action();
            }
        }
    }
}

Note that we can always add more extensions into this class, for me, I only have one above as I only require it, simple and only introduce when you need it :)

Eric De Carufel has written the more complete extensions as well in his blog post
And if you’re wondering why VS intellisense is giving you a false alarm that CheckAccess is not available for Dispatcher, Claus Konrad explained it in his blog post

Simple WPF .Net 4.0 DataGrid with MVVM example

Posted on Updated on

Had a discussion with my old colleague today, he’s having a weird problem updating a boolean property in the underlying data using the checkbox control in his WPF application.

When I did a quick look at his code, seems that he’s using a data table as the underlying data source for the data grid, unfortunately I have been only using simple POCO in my WPF application because of our application architecture of having separate application server which will do the data fetching from the DB. What I recommended him is to just try and use the simple POCO like we did in our app.

As it was pretty late at the office already, I promised him that I will give him some simple example if he want to give this a try, so I quickly fired up VS when I reached home and cooked a small app just to show how it works by having view model backing for the rows itself.

Below is when the application just started up, the 3 text boxes below will just display the current item/row values

Below is when we checked the checkbox, notice that the 3rd text box has changed to True as well from false.

And this can be achieved just through the WPF/MVVM bindings.

Just nice and simple ;)
The example can be downloaded from here

I did find some good references below about bindings through DataTable/DataSet:

http://msdn.microsoft.com/en-us/library/aa480226.aspx

http://www.codeproject.com/KB/WPF/WPFDataGridExamples.aspx

Setting Visibility of WPF Control through Binding

Posted on

Just found out that the Visibility property of WPF controls is not having true / false value.
So just by returning bool (IsControlVisible) like the code below won’t work:

<ContentControl Visibility="{Binding Path=IsControlVisible}"></ContentControl>

 

That’s because Visibility is an enumeration You will need to use a converter to convert the bool into the enum. Fortunately there is a BooleanToVisibilityConverter available so we need not create own custom converter.

Include this into the resources.

<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
 
And use it in the control binding
 
<ContentControl Visibility="{Binding Path=IsControlVisible, Converter={StaticResource BooleanToVisibilityConverter}}"></ContentControl>

 

Hope this helps ;)