我有一个像这样的控件:
[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), typeof(AutoCompleteBox), new PropertyMetadata(null, 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的这些问题?或者看到我在做什么有什么问题?
我会尝试检查绑定是否会用DebugConverter触发 – 检查 WinRT XAML Toolkit中的 BindingDebugConverter – 将其设置为绑定的转换器,并查看它是否以及何时中断(在转换或转换后是什么,正在设置什么值等等). ).如果这没有帮助 – 检查您的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, Culture=neutral, PublicKeyToken=b77a5c561934e089’ to type ‘IEnumerable’; BindingExpression: Path=’Persons’ DataItem=’ACBDP.BlankPageViewModel, ACBDP, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null’; target element is ‘ACBDP.AutoCompleteBox’ (Name=’null’); target property is ‘ItemsSource’ (type ‘IEnumerable’).