Showing posts with label wpf. Show all posts
Showing posts with label wpf. Show all posts

Monday, October 29, 2012

KnockoutJS tip : when to use brackets?

I simply love the knockout.JS framework. It makes the migration from silverlight to javascript / html so much more comfortable.

One point of confusion in knockout JS you might feel is when do you have to use brackets in front of observable and when can you ignore them? 

e.g. in the knockout intro tutorial : http://learn.knockoutjs.com/#/?tutorial=intro 

This: 

will work just as well as: 


Then whats the difference?  is actually a function since ko.observable returns a function : 



My solution:
In code ALWAYS use ().You have to, otherwise you will remove the ko.observable function on assignment which is bad. And on reading you would get the function not the value you wanted. 

In simple data-bind attributes NEVER use (). Because it will not work to two way data binding, i.e If I had bound value: firstName() to the input it would not have worked.  

In calculated data-bind attributes e.g. value: firstName() + lastName() , use brackets since you want one way binding and basically running arbitrary javascript :) 

Enjoy! 

Sunday, October 16, 2011

Enjoy your typography

If you enjoy typography here are a couple of links to bring a smile to your face.

First of all is the famous "So you need a typeface?" infographic.

(The original author has his website here : http://julianhansen.com/)

Next up there are the really hilarious shorts by college humour called Font Conference and Font Fight.

And if you have 50 minutes here is a nice talk by Rob Conery and Scott Hanselman with Bill Hill (the creator of cleartype) that you are sure to enjoy.

And if you want to have a deeper understanding of why typography matters here is "Magic of reading" by Bill hill in Microsoft Word format : www.billhillsite.com/osprey.doc
(Source http://billhillsblog.blogspot.com/2008/02/magic-of-reading.html)

Here is a short description of how cleartype works:

For a detailed discussion Wikipedia has an excellent article. Also interestingly WPF renderes all text in cleartype. But so does every windows by default starting from Vista.

Enjoy!

Thursday, September 1, 2011

The state of Flex Frameworks

As you might know I have been experimenting with Flex for a while. Due to the ability to target andoid/iOS/facebook in one go!

But the way I am wired I need to know just about everything about the technology before I start to get my feet wet. I learnt this with C#. Didn't know about reference types vs. value types after a whole year of coding! (although ... I do miss the careless abandon of my old coding ways)

I feel that now I have the language Actionscript down (I wrote a small book "Actionscript for C# developers" that I will share after its more stable) and have a fair understanding of the flex / flash apis. I now need to dive into the community work that has been done in flex.

Like silverlight / wpf (where I finally settled with MVVMLight ... and I know why I did that ;) ) I am going about searching for the most community accepted solution for flex. Fortunately I know about dependency injection, MVC (thanks to django), a lot about databinding (thanks to mvvm / silverlight / wpf) so its not a voyage of discovery rather a voyage of rediscovery.

Just FYI : With Silverlight / WPF it is clear to me that if I have ICommand delegate based implementation, a servicelocator implementation (and after MEF is officially a part .NET framework why go with any other?) , an INPC implementation and some form of App encompassing Mediator .... I am good to go! Now I need to figure out how these translate to Flex and what are the solutions proposed by the community.

Here are my two cents for flex:

Cairngorm (what was)
One thing is clear. Cairngorm is the official adobe solution : http://sourceforge.net/adobe/cairngorm/home/Home/ but is a no go for new projects. Its not really the ideal actionscript solution to the types of problems that are faced : http://archive.davidtucker.net/2009/10/13/the-current-state-of-flex-frameworks/
I do feel however that one should view how it was architectured before moving on to the community shiny frameworks.

Community (what is )
So now the question really comes down to which of these is the way to go. I am selecting the most popular solutions (high number of community supporters) here and not going with the completeness / quality. Because I am trying to be a late adapter for now :)

So heres the list I will be evaluating along with first opinions:



I took me about three months of active research and reading to fullly abridge the whole MVVM frameworks story for silverlight / wpf. I hope it will turn out faster for flex.

Till then enjoy!

Update October 2011:  It has become pretty clear to me that RobotLegs is the way to go. Infact it is one of the most watched Actionscript libraries on GitHub! 

Sunday, July 3, 2011

WPF Tip : Dependency Property changed callback not getting called

If you have a dependecy property of type IEnumerable databound to an INPC property simply raising a propertychanged event in the INPC property will not cause the changed callback of the dependency property to get called.

This is because apparently WPF internally uses an optimization where it checks the equality before calling the callback mentioned in the dependency property metadata. 

To force this callback you can assign the a new Enumerable instance to the INPC property. 

WPF Tip : Events Or commands which is called first?

The answer is Event. This is because the event is used to create the command by the control internally. Even click is handled before the command on a button :)

Wednesday, May 11, 2011

ObservableDictionary for Silverlight

I just migrated Dr. WPF's ObservableDictionary for WPF to silverlight. You can find the code here :
https://bitbucket.org/basarat/dictionarybasedvm/overview . Also at the same location is a sample.

The basic objective of making this is that you can Make a View Model properties to be exposed via a Dictionary rather than a Model. I would have preferred to work with dynamic but couldn't as described here :  http://stackoverflow.com/q/5949826/390330 For change notification on bound string based indexer properties the dictionary needs to implement INotifyCollectionChanged. There is not dictionary on the framework that comes with this.

I will also be updating the project to try and implement IDataErrorInfo.

Application Screenshot :

Where the xaml is :

Sunday, May 1, 2011

Simple styles to help you get started with WPF control styling

I did not know that blend came with simple styles in which the ControlTemplates are simplistic so you can easily master control styling in WPF without being bogged down into details.

Heres how you can use them.

  • In blend 4 create a new WPF application. 
  • In the assets panel type in Simple. You will now see a large list of controls as shown: 

  • Drag and drop any one of these onto the artboard. Edit the Template (Select a copy!) 
That is it. 
Check out how Simple the template for SimpleButton is! : 

If you have ever been overwhelmed by the default templates for various controls the simple styles are the way to go! 
Enjoy!

Thursday, March 31, 2011

Default constructor can be suppressed. But it is required for XAML instantiation

Well the title really say it all doesn't it. If you create a class with a constructor that takes any parameters then the compiler will not create the default constructor for you. In such a case if you try to create the object in XAML your code will compile (actually the BAML will be made so the compiler really doesn't know that you tried to call a default constructor when there isn't one) but you will get a runtime error in InitializeComponent(). Just so you know.

Enjoy!


WPF / Silverlight showing content in ControlTemplates

While styling the control template for TabItem for wpf I noticed that the content required to be displayed in the TabItem is actually the header property.

For this in the template ContentPresent with ContentSource="Header" was used.

But ContentSource is not present for Silverlight 4. So I decided to see how silverlight did it. Turns out it is simply ContentControl bound to the Header using TemplateBinding :



Seems obvious in retrospect.

Enjoy!

Binding Sources

The syntax of Binding is a source of much confusion to a lot of people (pun intended). But it is really not that hard. Especially once you look at all the possible sources:

  • ElementName (based on an element name present in the scope)
  • RelativeSource (based on a logical tree walk)
  • Source (based on resources)
  • If none of these properties is specified the path will be on the DataContext
Of course if no path is specified then you are binding directly to the source. 

In any case feel free to use the VisualStudio / Expression Blend databinding dialog to have software generate the syntax for you. 

Easy isn't it?
Enjoy!

Wednesday, March 30, 2011

Riagenic's RentConnect TabControl style (copy)

A friend of mine (who used to do winforms previously) saw the RentConnect application's image and fell in love with the look and feel instantly. Check out the original application image here : http://www.riagenic.com/archives/493


So I started showing how one would go about making such a look and feel in WPF / Silverlight.
First I showed him a metro button (a post on that later). Next I wanted to show him how the Available Tasks might be a styled TabControl / TabItems.

Based on Sacha's work (http://sachabarber.net/?p=322) I came up with this:


For selected Items I also added a scale X transform.
You can download all the code from here :
https://bitbucket.org/basarat/metrostyles



Monday, March 14, 2011

Some cool patterns for MVVM property initialization

This post is about how to setup properties commonly used in MVVM.

The ObservableCollection
I like to create a backing field property. Initilize the backing field immediately. Return the backing field in get. And clear then copy the items into the backing field in set. The performance of add might not be perfect but it is the only option I have I believe:


private ObservableCollection _OpenDocuments = new ObservableCollection();
public ObservableCollection OpenDocuments
{
    get { return _OpenDocuments; }
    set
    {
        _OpenDocuments.Clear();                
        foreach (var item in value)
        {
            _OpenDocuments.Add(item);
        }
    }
}


The RelayCommand
I got this pattern of the code from Karl : http://karlshifflett.wordpress.com/. Based on how he initializes his RelayCommand. Have a backing field. And in get check the backing field for null. If null create it. Finally return it.
Sample:

public RelayCommand _SaveStudent;
public RelayCommand SaveStudent
{
    get
    {
        if (_SaveStudent == null)
        {
            _SaveStudent = new RelayCommand(() => { Save(); }, () => { return CanSaveExecute(); });
        }
        return _SaveStudent;
    }

}



Enjoy!



Sunday, March 13, 2011

Hiding the wpf ribbon application menu

Setting The Application Menu to x:Null or simple not setting any value for the application menu does not work and you still see the ribbon menu button :


But it can be hidden by setting the Ribbon.ApplicationMenu to a dummy item and set its visibility to Collapsed.


You will (ofcourse) still see the button at design time but when you run the application it will be hidden :)


Saturday, March 12, 2011

Forcing the Aero Theme in your application

I have yet to find a theme that I am as satisfied with in WPF as the default aero theme that comes with the framework. But if you do not apply a theme to your application the look and feel of the WPF application will change according to the look and feel setup by the client.

But if you want your WPF application to always use the aero theme irrespective of the current client computer theme setting you can do that in simple steps.

Add a reference to PresentationFramework.Aero :
And set its property "CopyLocal" to true:

Finally add the following to your app.xaml:


<Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>                
                <ResourceDictionary Source="/PresentationFramework.Aero;component\themes/aero.normalcolor.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>


And now your application will use the aero theme irrespective of client settings.







Thursday, March 10, 2011

Ignorable design time namespace from Blend

Visual studio does not add it to files by default. And in new projects I create in Visual studio I find it annoying to create a random file just to get these namespaces and attribute out of it.

So here it is (tested on VS2010, WPF4). You can copy paste it into the root element of your xaml file :


xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"


if only xaml designer had a snippet option I would make one :)
Enjoy!

Tuesday, February 8, 2011

MVVMLight Extensions, Part: The MVVM Validation

MVVMLight is great. It is at the very least the most effective MVVM framework that is Blend / Visual Studio Design time friendly. The project focuses a lot on providing the minimum amount of built in functionality to give you the ability to make effective MVVM applications. This means that there are some areas (like validation) where MVVMLight does not add anything more that what is already available with WPF / Silverlight. So wanting to extend the library with your own extensions is a normal desire.

The Code (hosted by bitbucket)

Here is my attempt. You don't have to use it. I don't expect you to (you might want to add the code to your bag o tricks in your own mvvmlightextensions).

Here I explain what comes with the package:

A better way to add validation (Source)
The sample (kept as bare bones as possible to be simple):


We look at the model / the viewmodel and the view in turn.


Before you read about the Model and ViewModel check out snippets section. 


The Model
Its about time you move your models to object databases. With that just (2 things) :

  • Inherit from ModelBase and you neet all the goodness in the INotifyPropertyChanged and IDataErrorInfo.  

Just look at student.cs. There are two simple properties Name (string) / AdmissionDate (DateTime?) (both added with mvvminpcs snippet)

and implement:
  • override of string this[string columnname] added using mvvmde and mvvmdei snippets. Fill it up with your validation logic:



All in all about 100 keystrokes max (if you don't count the error strings :))
The ViewModel

  • Expose the Model as a property on the View (use a snippet of course):
  • Expose your commands (again use a snippet):


  • IMPORTANT Use base.UIValidataionErrorCount and ModelObject.Error.Count to determine if there are any errors (e.g return base.UIValidationErrorCount == 0 && this.Student.Errors.Count == 0 is used in the sample to determine if the save command can execute)



The View
Nothing much to do except that
  • inherit from ViewBase rather than UserControl:

  • Define a style for validation template and apply it in your View Xaml:
    <mle:ViewBaseEx.Resources>
            <!--Create a validataion control template for a TextBlock-->
            <ControlTemplate x:Key="validationTemplate">
                <DockPanel>
                    <TextBlock Margin="5,0,5,0" Foreground="Red" FontSize="16" VerticalAlignment="Center" Text="*" ToolTip="{Binding ElementName=errorAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}" />
                    <AdornedElementPlaceholder x:Name="errorAdorner" />
                </DockPanel>
            </ControlTemplate>
            <!--Set the Validation Error Template to the control template we just created-->
            <Style TargetType="{x:Type TextBox}">
                <Setter Property="Validation.ErrorTemplate" Value="{DynamicResource validationTemplate}" />
            </Style>
        </mle:ViewBaseEx.Resources>
  • And in all the bindings that are bound to the Model (view the ViewModel) add the following:
    NotifyOnValidationError=True, ValidatesOnDataErrors=True, ValidatesOnExceptions=True

That wasn't so hard was it.
Enjoy!

Monday, February 7, 2011

MVVMLight Extensions, Part: The Snippets


MVVMLight is great. It is at the very least the most effective MVVM framework that is Blend / Visual Studio Design time friendly. The project focuses a lot on providing the minimum amount of built in functionality to give you the ability to make effective MVVM applications. This means that there are some areas (like validation) where MVVMLight does not add anything more that what is already available with WPF / Silverlight. So wanting to extend the library with your own extensions is a normal desire. 


Here is my attempt. You don't have to use it. I don't expect you to (you might want to add the code to your bag o tricks in your own mvvmlightextensions).

The snippets can be categorized by Model and General: 

General
mvvmrc
For mvvm relay command expansion shown, Just fill in name / ExecuteFunction and CanExecuteFunction: 

Utilized in sample:

mvvminpcs:
For INotifyPropertyChanged using stacktrace: 
The RaisePropertyChanged function is defined in ViewModelBaseEx and therefore your ViewModel/Model needs to inherit from ViewModelBaseEx 
Used in sample application: 
Model
mvvmde:
If you Model inherits from ViewModelBaseEx you can use mvvmde for the data validation logic: 
Just fill in the property , the validation condition and the error message you want displayed.
For additional properties just use the mvvmdei snippet:


Used in the sample application: 






Saturday, January 22, 2011

Cinch and snippets love

Cinch comes with an awesome set of code snippets you can download here (from the cinch codeplex project page).

Installation
To install them just copy the .snippet files from the zip you downloaded to one of the following:
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC#\Snippets\1033\Visual C#
C:\Program Files\Microsoft Visual Studio 10.0\VC#\Snippets\1033\Visual C#

This is the default location for VS 2010 snippets as viewed from Tools > Code Snippets Manager > My Code Snippets.

You do not need to restart visual studio 2010 for these snippets to become effective.

Usage
In case you are unfamiliar with snippets usage. Just type in cinch and you get this:
press tab again and you get : 


Press a number for a particular snippet and press tab again. You should get the code expanded.
Some code snippets contain code that you need to copy into the constructor for your ViewModel.



Enjoy!

Tuesday, January 11, 2011

Bad Image quality in WPF ribbon

The ribbon from Microsoft performs great with XAML resources however it always made my images look bad. I actually avoided using it for this reason. But Sacha just posted a great solution here : http://sachabarber.net/?p=847 He did it for Images in WPF 4 in general. I just wanted to mention that it makes image quality in Ribbon improve as well. Here is the style he used:


<Window.Resources>
    <Style TargetType="{x:Type Image}">
        <Setter Property="RenderOptions.BitmapScalingMode"
               Value="HighQuality" />
    </Style>
</Window.Resources>

Tuesday, December 28, 2010

Having a setter for an Observable Collection

Here's another cool way to override the getter for an observable collection without breaking your MVVM:


private ObservableCollection<string> _AvailableColumns = new ObservableCollection<string>();
        public ObservableCollection<string> AvailableColumns
        {
            get { return _AvailableColumns; }
            set
            {
                _AvailableColumns.Clear();
                foreach (var item in value)
                {
                    _AvailableColumns.Add(item);
                }
            }
        }

Now you can use it like :


new RequiredColumn() {RequiredColumnName="BSC",DefaultValue="",AvailableColumns=AvilableColumns};


and it will not break your notification changes :)