views:

33

answers:

2

I'm just getting started with WPF. I have TextBox declared in xmal like so:

<TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Path=TestComplex.Something, Mode=TwoWay}"/>

In my code behind I have registered the property that I am trying to bind to like so:

public TestComplexObject TestComplex
    {
        get { return (TestComplexObject)GetValue(TestComplexProperty); }
        set { SetValue(TestComplexProperty, value); }
    }

    public static readonly DependencyProperty TestComplexProperty=
        DependencyProperty.Register("TestComplex", typeof(TestComplexObject ), typeof(MainWindow), new UIPropertyMetadata(new TestComplexObject ()));

The TestComplexObject class:

public class TestComplexObject : DependencyObject 
{
    public string Something
    {
        get { return (string)GetValue(SomethingProperty ); }
        set { SetValue(ExeLocationProperty, value); }
    }

    public static readonly DependencyProperty SomethingProperty =
        DependencyProperty.Register("Something", typeof(string), typeof(TestComplexObject), new UIPropertyMetadata("Test Text"));

}

As you can see I'm trying to bind the TextBox to TestComplex.Something, however when I run this all I get is a xmal parse exception,

"'The invocation of the constructor on type 'EmuRunner.MainWindow' that matches the specified binding constraints threw an exception.' Line number '6' and line position '9"

I really have no idea what I'm doing wrong here, can anyone help?

Thanks in advance.

A: 

The problem is this line:

set { SetValue(ExeLocationProperty, value); }

You are only allowed to call SetValue(SomethingProperty, value); in a setter for Something.

Femaref
That's not true. There's no required relationship between the names of dependency properties and the names of the CLR properties they're exposed as. That the CLR property `Foo` maps to the dependency property `FooProperty` is entirely a convention. In fact you can have multiple CLR properties that all set the same DP. A terrible, terrible idea, but it won't throw an exception.
Robert Rossney
A: 

I believe you will find that this question contains the answer to your problem.

Basically, your TestComplexObject isn't free threaded and thread safe (e.g. derived from System.Windows.Freezable). Type initializers for the two types (MainWindow and TestComplexObject) are (or could be) running simultaneously on different threads - which would cause a cross-threading exception (or worse) when the type initializer for MainWindow causes the type initializer for TestComplexObject to be called. The framework detects this potential and throws an exception.

Robert Rossney
Thanks very much for that, I'll check when I get home but that seems to be the problem.
bplus