【发布时间】:2011-03-17 02:22:51
【问题描述】:
我在数据绑定方面遇到了重大问题。
我的 MainPage.xml 中有一个带有 ItemControl 的堆栈面板:
<StackPanel>
<ItemsControl x:Name="TopicList">
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:TopicListItem Title="{Binding Title}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
然后,我将一个 IEnumerable 对象挂接到该对象上,该对象包含一个带有属性 Title 的对象。它在 MainPage.xaml.cs 中完成(我知道 LINQ 部分正在工作):
var resultStories = from story in resultXML.Descendants("story")
select new NewsStory {...};
Dispatcher.BeginInvoke(() => TopicList.ItemsSource = resultStories);
在我的自定义控件 TopicListItem 中,我创建了一个 DepenencyProperty 和相应的公共属性:
#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)
当我运行它并尝试设置 ItemSource 时,Title 属性出现错误:
System.TypeInitializationException:'NewsSync.TopicListItem 的类型初始化程序引发了异常。 ---> System.ArgumentException: 默认值类型与类型不匹配 财产。
--
附带说明:我尝试不为 Title 属性声明 DepenencyProperty,而只是将其作为公共字符串。但是后来我遇到了转换问题,它说我无法从 System.[...].Binding 转换为 System.String
所以我真的尝试了很多东西。
【问题讨论】:
标签: silverlight data-binding silverlight-4.0 dependency-properties