Attached Properties and Python script
While I'm trying to work around the xml:space issue from my last post, it is worthwhile to see how simple it was to create the attached property (which works fine, as long as your script doesn't need newlines...):
namespace Pythalon
{
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Media;
using IronPython;
using IronPython.Hosting;
public class PythonScript
{
#region DependencyProperty Declarations
private static PropertyMetadata ScriptPropertyMetadata = new PropertyMetadata(new SetValueOverride(PythonScript.SetScriptValueOverride));
public static DependencyProperty ScriptProperty = DependencyProperty.RegisterAttached("Script", typeof(string), typeof(PythonScript), ScriptPropertyMetadata);
#endregion DependencyProperty Declarations
private string script;
private PythonEngine pythonEngine = new PythonEngine();
private FrameworkElement target;
public PythonScript(FrameworkElement target, string script)
{
this.target = target;
this.script = script;
this.InitializeModuleEnvironment();
if (target.IsLoaded)
{
this.Execute();
}
else
{
this.target.Loaded += new RoutedEventHandler(target_Loaded);
}
}
private void InitializeModuleEnvironment()
{
this.pythonEngine.ExecuteFile("Startup.py");
this.pythonEngine.SetVariable("Target", this.target);
foreach (Visual v in VisualOperations.GetChildren(this.target))
{
string name = (string)v.GetValue(FrameworkElement.NameProperty);
if (!String.IsNullOrEmpty(name))
{
this.pythonEngine.SetVariable(name, v);
}
}
}
void target_Loaded(object sender, RoutedEventArgs e)
{
this.Execute();
}
public void Execute()
{
this.pythonEngine.Execute(this.script);
}
public override string ToString()
{
return this.script;
}
#region DependencyProperty Infrastructure
public static void SetScriptValueOverride(DependencyObject o, object value)
{
string script = value as string;
FrameworkElement target = o as FrameworkElement;
if ((target != null) && (script != null))
{
PythonScript pyScript = new PythonScript(target, script);
}
}
public static string GetScript(DependencyObject d)
{
return (string)d.GetValue(PythonScript.ScriptProperty);
}
public static void SetScript(DependencyObject d, string value)
{
d.SetValue(PythonScript.ScriptProperty, value);
}
#endregion DependencyProperty Infrastructure
}
}