【发布时间】:2011-05-05 10:45:00
【问题描述】:
对不起我的英语。 我尝试编写由弹出窗口中的 TextBox、Popup 和 ListBox 组成的 UserControl(SearchTextBox...simmillar Firefox 搜索文本框)。我需要在我的应用程序中动态更改 ListBox 的 ItemsSource。所以我在 UserControl 中使用 DependencyProperty:
//STextBox UserControl Code-Behind
public partial class STextBox : UserControl
{
public static readonly DependencyProperty ItemsSourceProperty;
static STextBox()
{
ItemsSourceProperty = DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(STextBox),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsArrange, new PropertyChangedCallback(OnItemsSourceChanged)));
}
public IEnumerable ItemsSource
{
get
{
return (IEnumerable)GetValue(STextBox.ItemsSourceProperty);
}
set
{
SetValue(STextBox.ItemsSourceProperty, value);
}
}
private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
STextBox c = (STextBox)d;
c.ItemsSource = (IEnumerable)e.NewValue;
}
我不能在我的应用程序中使用与 ItemsSource 的绑定,因为我的 ListBox-ItemsSource 的两个列表是从数据库记录中动态创建的。我在代码中设置了 ItemsSource: //我的应用程序代码隐藏
switch (SomeIF)
{
case 0:
sTextBox.ItemsSource = list1;
break;
case 1:
sTextBox.ItemsSource = list2;
break;
}
但是什么也没发生。我确切地知道 OnItemsSourceChanged 方法已被触发,但从未将新值分配给 ItemsSource。我做错了什么?
【问题讨论】:
-
如何使用 UserControl 的 ItemsSource 属性?你把它绑定在某个地方吗?
-
不,我不使用我的 UserControl 的绑定
-
那么当您分配 ItemsSource 时,您期望会发生什么?如果这个属性没有在任何地方使用,当然什么都不会发生……你可能需要将它绑定到 ListBox 的 ItemsSource 属性。
-
@mirymir 我创建了一个简单的项目来重现您的问题,并且......一切正常。也许您应该更详细地描述情况,甚至提供测试项目。
-
@Pavlo 我希望我的 ListBox 的 ItemsSource 将设置为 list1 或 list2,但这没有发生。我不能使用绑定,因为 list1 和 list2 在我写的时候会即时创建。