我的 Custom Control
来自 ItemsControl
。
我从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
中指定价值?
答案 0 :(得分:0)
每当您向ObservableCollection添加数据时,只需在此之前添加构造函数。这是我惯常的做法。
例如,
Collection = new ObservableCollection<string>();
...add data to the collection here
视您的情况而定。
修改强>
如果您想在自定义控制级别上使用解决方案,可以尝试以下方法:
var tb = d as BTextBox;
if (((tb.ItemsSource as IList) == null))
tb.ItemsSource = new IList<string>(); // or new ObservableCollection, List, or any suitable datatype, just to give default values
if ((e.NewValue != null) && ((tb.ItemsSource as IList) != null)) { // probably remove the checking for ((tb.ItemsSource as IList) != null) since we initialized it
...
答案 1 :(得分:0)
我们可以在添加项目之前添加项目,我们需要创建一个实例
if(this.ItemsSource == null)
{
this.ItemsSource = (new List<object>()).AsEnumerable();
}
(tb.ItemsSource as IList).Add(item);
现在,它不会抛出任何 NULL
参考例外。