【发布时间】:2017-01-23 03:02:36
【问题描述】:
我有一个从 ItemsControl 派生的 Custom Control。
我的想法来自Two-Way Binding Issue of Unknown Object in WPF Custom Control Dependency Property
在上面的问题中,他们在视图模型中使用了集合
private ObservableCollection<string> _collection = new ObservableCollection<string>();
public ObservableCollection<string> Collection
{
get { return _collection; }
set
{
_collection = value;
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Collection"));
}
}
XAML 代码是
<Window x:Class="SampleControl.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SampleControl"
Title="MainWindow" Height="400" Width="525">
<Grid>
<local:BTextBox
ItemsSource="{Binding Collection}"
ProviderCommand="{Binding AutoBTextCommand}"
AutoItemsSource="{Binding SuggCollection}" />
</Grid>
</Window>
如果我删除了new ObservableCollection<string>();,它就会变成
private ObservableCollection<string> _collection;
public ObservableCollection<string> Collection
{
get { return _collection; }
set
{
_collection = value;
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Collection"));
}
}
现在属性 Collection 持有值 NULL。此属性绑定在ItemsSource 中。那么,如何将数据推送到 ItemsSource 中
CustomControl 方法是
private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
var tb = d as BTextBox;
if ((e.NewValue != null) && ((tb.ItemsSource as IList) != null)) {
foreach (var item in e.NewValue as IEnumerable) {
(tb.ItemsSource as IList).Add(item);
}
}
}
在这个方法中,它检查NULL,如果ItemsSource是NOT NULL,则推送数据。
if ((e.NewValue != null) && ((tb.ItemsSource as IList) != null))。如果 ItemsSource 是 NOT NULL,那么只有这样项目才会被推入集合 (tb.ItemsSource as IList).Add(item);
请帮助我,如何在 Null-able IEnumerable 中分配值?
【问题讨论】:
-
IF the ItemsSource is NOT NULL, then it pushes the data有点模糊...... -
@JeroenvanLangen 请看上面的方法,它会检查
NULL~if ((e.NewValue != null) && ((tb.ItemsSource as IList) != null))。如果 ItemsSource 不为 NULL,那么只有项目才会被推入集合(tb.ItemsSource as IList).Add(item);。 -
但是,您将
Collection绑定到 Xaml 中的 ItemsSource,但您还将这些项目添加到AutoItemsSource? -
当我在 xaml 中绑定一个项目时,我只创建集合.._(在构造函数中)_
-
为什么不使用这个:
tb.ItemsSource = e.NewValue;
标签: c# wpf list custom-controls ienumerable