Write a GUI in Powershell – Part 4

4a. Create converter in C# for data binding for the same reason, Powershell doesn’t support C# interface.

using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows.Data;
using System.Management.Automation;

public class ConverterWrap : IValueConverter
{
public Func<object, Type, object, CultureInfo, PSObject> ConvertPS;
public Func<object, Type, object, CultureInfo, PSObject> ConvertBackPS;
public int debugLevel = 0;

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
try
{
DebugPrint("ConverterWrap: Convert: ");
PSObject p = ConvertPS(value, targetType, parameter, culture);
if (p == null)
{
DebugPrint("ConverterWrap: ConvertBack: null");
return null;
}
else
{
//Object o = p.ImmediateBaseObject;
Object o = p.BaseObject;
return o;
}
}
catch (Exception e)
{
DebugPrint(e.Message);
return System.Windows.DependencyProperty.UnsetValue;
}
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
try
{
DebugPrint("ConverterWrap: ConvertBack: ");
PSObject p = ConvertBackPS(value, targetType, parameter, culture);
if (p == null)
{
DebugPrint("ConverterWrap: ConvertBack: null");
return null;
}
else
{
DebugPrint("ConverterWrap: ConvertBack: " + p + "\t" + p.GetType());
//Object o = p.ImmediateBaseObject;
Object o = p.BaseObject;
//DebugPrint("ConverterWrap: ConvertBack: " + o + "\t" + o.GetType());
return o;
}
}
catch (Exception e)
{
DebugPrint(e.Message);
return System.Windows.DependencyProperty.UnsetValue;
}

}

protected void DebugPrint(String s)
{
if (debugLevel == 1)
{
Console.WriteLine(s);
}
}
}

4b. Add it to Powershell

$csharp2=Get-Content (Join-Path $path "ConverterWrap.cs") -Raw
Add-Type -TypeDefinition $csharp2 -ReferencedAssemblies @("PresentationFramework";"WindowsBase")

Advertisements
This entry was posted in C#, Powershell, XAML. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

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