与在的ItemsSource IEnumerable的默认值替换NULL [英] Replace NULL with a default Value in an ItemsSource IEnumerable
问题描述
我有一个 自定义控制
衍生自 的ItemsControl
I'm having a Custom Control
derived from an ItemsControl
.
在上面的问题,他们使用集合中的视图模型
In the above Question, they use the Collection in the View Model
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代码是
The XAML Code is
<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>
如果我删除了新的ObservableCollection<串>();
那么它将成为
If I removed the new ObservableCollection<string>();
then it will became
private ObservableCollection<string> _collection;
public ObservableCollection<string> Collection
{
get { return _collection; }
set
{
_collection = value;
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Collection"));
}
}
现在该物业的 收藏
保存值 NULL
。此属性是在的ItemsSource
绑定。所以,我怎么可能将数据推入的ItemsSource
Now the Property Collection
hold the value NULL
. This Property is bind in the ItemsSource
. So, how could I push the data into the ItemsSource
CustomControl方法是
The CustomControl Method is
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
,然后它推动数据。
In this method, it checks for NULL
, IF the ItemsSource
is NOT NULL
, then it pushes the data.
IF((e.NewValue!= NULL) &功放;及(!(tb.ItemsSource为IList的)= NULL))
。如果在 的ItemsSource
为 NOT NULL
,然后才把项目被推到集合(tb.ItemsSource作为IList的)。新增(项目);
请帮助我,如何分配值在 为空的的IEnumerable
?
Kindly assist me, how to assign the Value in a Null-able IEnumerable
?
推荐答案
我们可以添加项目,添加项目之前,我们需要创建一个实例
We Can add the Item, before adding the Item we need to create an Instance
if(this.ItemsSource == null)
{
this.ItemsSource = (new List<object>()).AsEnumerable();
}
(tb.ItemsSource as IList).Add(item);
现在,它不会引发任何的 NULL
参考例外
Now, it won't throw any NULL
Reference exception.
这篇关于与在的ItemsSource IEnumerable的默认值替换NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!