views:

364

answers:

2

I am getting a run-time error when I use DataBinding, and it is driving me crazy. I have a simple UserControl that I have defined, let's call it SillyControl. Separately, I have a collection

ObservableCollection<MyClass> myObjects;

and a ListBox called SillyListBox which is bound to this ObservableCollection via: SillyListBox.ItemsSource = myObjects; The ListBox is defined in XAML as so:

<ListBox x:Name="SillyListBox">
 <ListBox.ItemTemplate>
  <DataTemplate>
    <MyControls:SillyControl TestString="{Binding Name}" />
  </DataTemplate>
 </ListBox.ItemTemplate>
</ListBox>

So, whenever an object is added to the collection myObjects, a new SillyControl should be added to the ListBox and the property TestString of that SillyControl should be bound to the Name property of the MyClass object it represents.

This doesn't work. It compiles fine, but when I run the program, it gives me a nasty runtime error - System.Windows.Markup.XamlParseException and below that something that says AG_E_PARSER_BAD_PROPERTY_VALUE.

Now, if I simply remove the Binding, give TestString a fixed value, for instance, the error disappears. It is also possible for me to define a TextBlock control instead of a SillyControl and successfully use binding on it. What on Earth is causing this to happen?

Update: As requested, here is how SillyControl is defined:

public partial class SillyControl : UserControl
{
    private string testString;
    public string TestString
    {
        get { return testString; }
        set { testString = value; }
    }

    public SillyControl()
    {
        InitializeComponent();
    }
}

The XAML is truly barebones. I am using the default XAML, so it is nothing more than an empty Grid.

UPDATE 2: I have created a very simple test project for download that recreates the problem.

+1  A: 

MyClass needs to implement INotifyPropertyChanged: http://weblogs.asp.net/joelvarty/archive/2008/11/17/silverlight-databinding-the-observable-collection.aspx

Jonathan Parker
I agree that would be good but why would not implementing that interface result in the error. It would just mean that changes made to the property value would fail to make it into the UI but it shouldn't cause this error
AnthonyWJones
MyClass was implementing INotifyProperty when this error occurred. I also tested with INotifyProperty removed. No go either way.
JubJub
+1  A: 

Turns out that the property being bound to must be a DependencyProperty.

JubJub