因为我知道已经发布了很多关于依赖属性的帖子,所以我一直在搜索和搜索,但我只是还没有看到任何有有效解决方案的东西。我正在尝试将我的 ViewModel 中的 ObservableCollection 绑定到我的 AutoCompleteBox。我的 ViewModel 正在返回数据,Getter 被击中。但是,在那之后,控件的 SetValue 或 OnItemsSourcePropertyChanged 不会触发。有什么想法可能是错的吗?
我有这样的控制:
[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 时遇到过这些问题吗?或者看到我在做什么有什么问题?