[contentproperty(Name = "ItemsSource")] public partial class autocompletebox : Control { //local stuff private ListBox lb; private List<Person> _items; private ObservableCollection<Person> _view; public autocompletebox() : base() { DefaultStyleKey = typeof(autocompletebox); Loaded += (sender,e) => ApplyTemplate(); } protected override void OnApplyTemplate() { this.lb = this.GetTemplateChild("Selector") as ListBox; base.OnApplyTemplate(); } #region ItemsSource public IEnumerable ItemsSource { get { return GetValue(ItemsSourceProperty) as ObservableCollection<Person>; } set { SetValue(ItemsSourceProperty,value); } //Never gets called } public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register( "ItemsSource",typeof(IEnumerable),typeof(autocompletebox),new PropertyMetadata(null,OnItemsSourcePropertyChanged)); private static void OnItemsSourcePropertyChanged(DependencyObject d,DependencyPropertyChangedEventArgs e) { //Never gets called :( } #endregion public String SearchText { get { return GetValue(SearchTextProperty) as String; } set { SetValue(SearchTextProperty,value); } } public static readonly DependencyProperty SearchTextProperty = DependencyProperty.Register( "SearchText",typeof(String),OnSearchTextPropertyChanged)); private static void OnSearchTextPropertyChanged(DependencyObject d,DependencyPropertyChangedEventArgs e) { //gets fired when loaded,with data being bound } }
以下是它如何使用控件:
<toolkit:autocompletebox Grid.Row="5" Grid.Column="2" ItemsSource="{Binding Persons,Mode=TwoWay}" SearchText="WhatTheHell"/>
作为测试并且为了简单起见,我为SearchText创建了一个String DependencyProperty.如果我绑定SearchText,它会正常工作,调用OnSearchTextPropertyChanged:
<toolkit:autocompletebox Grid.Row="5" Grid.Column="2" ItemsSource="{Binding Persons,Mode=TwoWay}" SearchText="{Binding SearchText}"/>
有没有人遇到WinRT的这些问题?或者看到我在做什么有什么问题?
解决方法
如果这没有帮助 – 检查您的DataContext是否设置正确.
*编辑1
如果您要查看的是绑定集合的项目中的更改 – 您可以检查ItemsSource是否为INotifyCollectionChanged,如果为true,则订阅CollectionChanged事件以查看更改.否则 – 您可以修改您的控件以从ItemsControl继承并覆盖GetContainerForItemOverride和IsItemItsOwnContainerOverride之类的方法.
*编辑2
看起来Windows 8 Consumer Preview框架中有a bug与使用IEnumerable作为依赖属性的类型有关.使用object作为类型可以解决问题.如果启用本机代码调试,您将看到此绑定异常:
Error: Converter Failed to convert value of type ‘System.Collections.ObjectModel.ObservableCollection`1[[ACBDP.Person,ACBDP,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null]],System,Version=4.0.0.0,PublicKeyToken=b77a5c561934e089’ to type ‘IEnumerable’; BindingExpression: Path=’Persons’ DataItem=’ACBDP.BlankPageviewmodel,PublicKeyToken=null’; target element is ‘ACBDP.autocompletebox’ (Name=’null’); target property is ‘ItemsSource’ (type ‘IEnumerable’).
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。