I am having major problem in Data Binding.
I have a stackpanel with an ItemControl in my MainPage.xml:
<StackPanel>
<ItemsControl x:Name="TopicList">
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:TopicListItem Title="{Binding Title}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
Then I hook a IEnumerable object on to that that contains an object with the property Title on it. It is done in the MainPage.xaml.cs (and I know that the LINQ part is working):
var resultStories = from story in resultXML.Descendants("story")
select new NewsStory {...};
Dispatcher.BeginInvoke(() => TopicList.ItemsSource = resultStories);
And inside my custom control TopicListItem I have created a DepenencyProperty and corresponding public property:
#region Title (DependencyProperty)
/// <summary>
/// Title
/// </summary>
public String Title
{
get { return (String)GetValue(TitleProperty); }
set { SetValue(TitleProperty, value); }
}
public static readonly DependencyProperty TitleProperty =
DependencyProperty.Register("Title", typeof(String), typeof(TopicListItem),
new PropertyMetadata(0, new PropertyChangedCallback(OnTitleChanged)));
private static void OnTitleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((TopicListItem)d).OnTitleChanged(e);
}
private void OnTitleChanged(DependencyPropertyChangedEventArgs e)
{
throw new NotImplementedException();
}
#endregion Title (DependencyProperty)
When I run this and it tries to set the ItemSource an error comes up on the Title property:
System.TypeInitializationException: The type initializer for ‘NewsSync.TopicListItem threw an exception. —> System.ArgumentException: Default value type does not match type
of property.
—
As a side note: I have tried not declaring a DepenencyProperty for the Title property and just having it as a public String. But then I get conversion issues where it says that I cannot convert from System.[...].Binding to System.String
So I have really tried many things.
This bit is your problem:-
Note the first parameter of the
PropertyMetadataconstructor is the default value of the dependency property. You have registered it as atypeof(String)but you are using anInt32(0) as the initial value. Usenullinstead. You could also just use:-Since your code will throw an exception currently when a value is assigned to
Title. You only need to specify aPropertyChangedCallbackif you actually have something want to do when the property changes.