0

I'm trying to build out some WPF components using LINQPad as a test bench. Building it out using a Xaml string and instantiating the classes using XamlServices. This works fine with simple Xaml but I noticed the moment I add bindings, it fails due to some bogus exception. I tried the same on a small test WPF app and I still get the same issue.

private StackPanel MakePanel()
{
    var panel = (StackPanel)XamlServices.Parse($@"
<StackPanel xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>
    <StackPanel Orientation='Horizontal'>
        <Label Width='100'>Source:</Label>
        <TextBox Width='500' Text='{{Binding Source}}' />
        <Button>...</Button>
        <Button>Scan</Button>
    </StackPanel>
    <StackPanel Orientation='Horizontal'>
        <Label Width='100'>Destination:</Label>
        <TextBox Width='500' Text='{{Binding Destination}}' />
        <Button>...</Button>
    </StackPanel>
</StackPanel>
");
    return panel;
}

Application: WpfTest.exe
CoreCLR Version: 6.0.422.16404
.NET Version: 6.0.4
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Windows.Markup.XamlParseException: 'The invocation of the constructor on type 'WpfTest.MainWindow' that matches the specified binding constraints threw an exception.' Line number '6' and line position '9'.
---> System.Xaml.XamlObjectWriterException: Provide value on 'System.Windows.Data.Binding' threw an exception.
---> System.Windows.Markup.XamlParseException: A 'Binding' cannot be set on the 'Text' property of type 'TextBox'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.

This is definitely bogus because TextBox is a DependencyObject so something must be disconnected somewhere. If I moved the actual string contents into a Xaml file, it works no problem.

Is there some setup or dependencies I need to include to be able to use XamlServices with bindings? Why is this failing?

Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
  • @Clemens: I wouldn't say this is a duplicate of those. Sure in the end, the solution was to use the classes described to parse, but the problem was that one specific implementation seemed to work only sometimes and we're trying to find out why. Any way, problem solved – Jeff Mercado May 01 '22 at 20:06

1 Answers1

0

I think I figured it out. System.Xaml.XamlServices I think was meant for use with generic xaml and not necessarily configured for consuming WPF xaml. So it doesn't load all the necessary dependencies and namespace mappings that would be used in a WPF application. And apparently, System.Windows.Data.Binding is not a part of it's default setup.

Switching over to use System.Windows.Markup.XamlReader.Parse() instead is aware of all the WPF-related classes and is able to parse this with no problems.

Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272