RSS

Command BindingParameter Bool

14 Apr

Have you ever been in the case, that you need a BindingParameter of Type boolean? If you try to set it directly via XAML by using True or False as CommandParemer you will get stuck, because this will not work. You can’t directly cast an object of type String to an object of type bool.
Using following won’t work.

ICommand MyCommand = new SimpleCommand<bool,object>(CanExecute,Executed);
private bool CanExecute(bool b){}

This piece of code is referred to Cinch MVVM, other Frameworks that uses the RelayCommand have the same issue.

<Button Command={Binding MyCommand} CommandParameter=True/>

You will get the exception that you cannot cast string to bool.
A solution would be to create a object of type boolean via XAML in following way:

Import following namespace:

  xmlns:System="clr-namespace:System;assembly=mscorlib" 

Then use this piece of code

<Button Command={Binding MyCommand}>
  <Button.CommandParameter>
    <System:Boolean>True</System:Boolean>
  </Button.CommandParameter>
</Button>

But, this is not what I wanted. You certainly agree with me that doing this all the time when you need a boolean in XAML can be very anoying. So what can you use as solution?
What I did is creating a helper class named BooleanHelper providing a property for each of both boolean values. Below you can see how i did that

public static class BooleanHelper
{
    public static bool False
    {
        get { return false; }
    }
     public static bool True
    {
        get { return true; }
    }
}

So now you can easily use this in following way:

<Button Command={Binding Path=MyCommand, CommandParameter="{x:Static BooleanHelper.True}">

Nice, isn’t it?

Advertisements
 
Leave a comment

Posted by on April 14, 2011 in C-Sharp, WPF

 

Tags:

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: