September 6, 2008

How to make an object from string in Silverlight 2 (to avoid AG_E_PARSER_MISSING_DEFAULT_NAMESPACE error)

XamlReaderを用いて文字列からFrameworkElementオブジェクトをつくるときには明示的に既定のXML名前空間を指定しなければならない。たとえば、xmlns='http://schemas.microsoft.com/client/2007'と指定する。そうしないとAG_E_PARSER_MISSING_DEFAULT_NAMESPACEというエラーが。Silverlight 2 beta 2。

ちなみにJScriptのCreateFromXAMLで名前空間は明示しなければhttp://schemas.microsoft.com/client/2007

For XamlReader, the required root element must specify a default XML namespace. This is typically the Silverlight client namespace, http://schemas.microsoft.com/client/2007. For CreateFromXAML the default XML namespace is implicitly assumed to be http://schemas.microsoft.com/client/2007 if not specified.
string xaml = @"<Button xmlns='http://schemas.microsoft.com/client/2007'" +
"Content='foo' Width='60' Height='20' />";
// XamlParseException (AG_E_PARSER_MISSING_DEFAULT_NAMESPACE) will occur if you write
// string xaml = @"<Button Content='foo' Width='60' Height='20' />"
FrameworkElement element = XamlReader.Load(xaml) as FrameworkElement;
hoge.Children.Add(element);

Cf.
Using XamlReader.Load
CreateFromXAML
// Create the MouseLeftButtonUp event handler for the root Canvas object.
function onMouseLeftButtonUp(sender, eventArgs)
{
// Retrieve a reference to the plug-in.
var plugin = sender.getHost();

// Define a XAML fragment and create it.
var xamlFragment = '<TextBlock Canvas.Top="200" Text="Click for more info..." />';
textBlock = plugin.content.createFromXaml(xamlFragment, false);

// Add the XAML fragment as a child of the root Canvas object.
sender.children.add(textBlock);
}

No comments:

Post a Comment