我在数据绑定(bind)方面遇到了重大问题。
我的 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
和相应的公共(public)属性:
#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: The type initializer for 'NewsSync.TopicListItem threw an exception. ---> System.ArgumentException: Default value type does not match type of property.
--
附带说明:我尝试不为 Title 属性声明 DepenencyProperty,而只是将其作为公共(public)字符串。但后来我遇到了转换问题,它说我无法从 System.[...].Binding
转换为 System.String
所以我真的尝试了很多东西。
最佳答案
这就是你的问题:-
public static readonly DependencyProperty TitleProperty =
DependencyProperty.Register("Title", typeof(String), typeof(TopicListItem),
new PropertyMetadata(0, new PropertyChangedCallback(OnTitleChanged)));
请注意,PropertyMetadata
构造函数的第一个参数是依赖项属性的默认值。您已将其注册为 typeof(String)
,但您使用 Int32
(0) 作为初始值。请改用 null
。您也可以只使用:-
public static readonly DependencyProperty TitleProperty =
DependencyProperty.Register("Title", typeof(String), typeof(TopicListItem), null);
因为当前将值分配给 Title
时,您的代码将引发异常。如果您确实想要在属性更改时执行某些操作,则只需指定 PropertyChangedCallback
。
关于silverlight - ItemsControl 中的数据绑定(bind)到自定义 UserControl 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3267483/