How to create a generic list using reflection

Reflection is a very powerful feature which allows you to do lots of crazy things.
But sometimes you want to create a generic class which can be really annoying if you dont know how to do it.

If you try to do it as usual then you will receive an exception.
An example would be

var myType = typeof (double);
var list = (List<myType>) Activator.CreateInstance(typeof (List<myType>), null);

The compiler tells you that a type or namespace is expected and not myType!

 

In order to do that you can use the MakeGenericType method to add the generic types to the List and after that you can create the instance

var myGenericType = typeof(List<>).MakeGenericType(new []{typeof(double)});
var myList = (List<double>)Activator.CreateInstance(myGenericType);

Note that the MakeGenericType method only creates the type which then is used to create an object in the next line

Extension Methods

Extension Methods are a nice way to add some extra functionality to a already existing class.
I use them for several tasks which are needed quite often. Such as the “raising” of an event or just the running of an action in the correct thread.
Therefore I decided to post the most important Extension Methods here.

When “raising” (fire) an event it is really annoying that we always have to check if the event is not null.
This results in a quite long code and we have always to repeat the same thing again.

Example:

public event EventHandler<EventArgs> MyEvent;

protected void RaiseMyEvent()
{
   if(MyEvent != null)
      MyEvent(this, EventArgs.Empty);
}

Using this extension method

/// <summary>
/// This method raises the given event with the given sender and EventArgs
/// </summary>
/// <typeparam name="T">The type of the event handler</typeparam>
/// <param name="eventHandler">The event handler</param>
/// <param name="sender">The sender</param>
/// <param name="e">The event args</param>
public static void Raise<T>(this EventHandler<T> eventHandler, Object sender, T e) where T : EventArgs
{
	if (eventHandler != null)
	{
		eventHandler(sender, e);
	}
}

it is possible to raise the event with that

public event EventHandler MyEvent<EventArgs>;

MyEvent.Raise(this, EventArgs.Empty);

Another example where Extension Methods are really useful is when you want to ensure that an action / function is executed in the right thread.
Usually you have to check whether you actually are in the right thread and invoke if necessary.

example:

public void MyMethod()
{
     if(myDispatcher.CheckAccess())
     {
        DoSomething();
     }
     else
     {
        myDispatcher.Invoke(new Action(MyMethod));
     }
}

In order to reduce this “useless” code we can use the following extension method

		/// <summary>
		/// This method automatically executes the given action in
		/// the correct thread.
		/// </summary>
		/// <param name="source">The source of the method call</param>
		/// <param name="func">The function which should be executed in the right thread</param>
		public static void Dispatch(this Dispatcher source, Action func)
		{
			if (source.CheckAccess())
				func();
			else
				source.Invoke(func);
		}

And here an example how to call it

myDispatcher.Dispatch(DoSomething);

More useful extension methods will follow…

[WPF] How to change the width of a Scrollbar (Scrollviewer)

If you are programming applications which should be used on a touch screen then you may have encountered the problem that it is tricky to use the scrollbar with the finger.
Because the default scrollbar is to small.

If you want to adjust the width of all scrollbars in your application you can put this piece of code into you resources

        <Style x:Key="{x:Type ScrollBar}" TargetType="{x:Type ScrollBar}">          
                <Setter Property="MinWidth" Value="35" />
                <Setter Property="Width" Value="35" />
        </Style>

Visual Studio 2010 has been released

Hello everybody,

Visual Studio 2010 has been released a few hours ago.
You can download it here:

[WPF] Custom ValidationRule with an additional parameter

Hello,

maybe you ever had the problem that you wanted to create a custom validationrule but you need some kind of an extra parameter.
But it seems that there is no straightforward way to do that.

So I used this workaround in order to achieve that.
In this example I will validate a string. The parameter gives the length if the string is shorter then it is valid else not.

First of all we have to create our custom ValidationRule

public class MyStringLengthValidationRule : ValidationRule
  {
    /// <summary>
    /// Gets or sets the maximal length of the string
    /// </summary>
    public int Length { get; set; }

    /// <summary>
    /// Checks if the string is valied
    /// </summary>
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
      if (value.ToString().Length <= Length)
         return new ValidationResult(true, null);
      return new ValidationResult(false, "The string is to long");
    }
  }

All right. Here you see this simple ValidationRule with our additional property (Length).
We can not use DependencyProperties because ValidationRule does not extend DependencyObject therefore we have to use this property.

The second step is to assign our ValidationRule to a control

        <TextBox>
            <TextBox.Text>
                <Binding Path="MyText">
                    <Binding.ValidationRules>
                        <utils:MyStringLengthValidationRule Length="{Binding MyLength}" />
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>

You may think that it works like this but it does not. Since the Length property is not a DependencyProperty we can not directly bind to it.
But there exists a nice workaround. We can just use a so-called proxy which allows us to bind values to normal properties.
I used the proxy from this blog: http://www.11011.net/wpf-binding-properties

The version using the proxy looks like this

<utils:Proxy In="{Binding MyLength, Mode=OneWay,UpdateSourceTrigger=PropertyChanged}" Out="{Binding ElementName=strLengthValidationRule, Path=Length}" /> 
<TextBox>
  <TextBox.Text>
     <Binding Path="MyText">
         <Binding.ValidationRules>
            <utils:MyStringLengthValidationRule x:Name="strLengthValidationRule" />
          </Binding.ValidationRules>
       </Binding>
  </TextBox.Text>
</TextBox>

All right now it should work.

I attached the demo project. Where you can specify the maximal length (upper TextBox) of the string in the TextBox at the bottom.
Note that the Validation will only be updated when the value of the TextBox was changed!

The attached file is a rar file. I just have to add the doc extension because else I can not upload it.
Change the extension in .rar then you can extract it. (It contains the demo project as a VS 2010 Beta solution)
ValidatorWithParameter.rar (doc)

[WPF] Set Attached Properties (Grid.Column, Grid.Row, Canvas.Top, Canvas.Left, etc.) in C# Code

Hello everybody,

if you tried to create a Grid, Canvas or a DockPanel in C# problem than you probably had the problem that you do not know how to add the children to a specific column, row or whatever.

These properties are so called Attached Properties. And you can not see them if you call textBox.Grid.Row in the C# code.

Here an example

<Grid>
   <TextBox Grid.Row="0" Grid.Column="0" />
</Grid>

But you can not do the following in your C# Code

<pre>Grid grid = new Grid();
TextBox txt = new TextBox();
txt.Grid.Column = 1; //Not possible!

But you can do the following

//Set the Grid.Row Attached Property of the TextBox txt to 0
Grid.SetRow(txt, 0);
//Set the Grid.Column Attached Property of the TextBox txt to 0
Grid.SetColumn(txt,0);

It works in the same way for all other Attached Properties

First version of MGConfigurationManager is released!

Hello everybody,

today I managed it to release the first version of the MGConfigurationManager.
It is a simple application which helps you to localize you program (if you are using the MGLocalizer).

Note that it is in the beta stadium and has just been tested by me 🙂

Have a look here
MGConfigurationManager

Here you see a screenshot