I'm having a Custom Control
derived from an ItemsControl
.
I got the idea from Two-Way Binding Issue of Unknown Object in WPF Custom Control Dependency Property
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"));
}
}
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>
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"));
}
}
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
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);
}
}
}
In this method, it checks for NULL
, IF the ItemsSource
is NOT NULL
, then it pushes the data.
if ((e.NewValue != null) && ((tb.ItemsSource as IList) != null))
. If the ItemsSource
is NOT NULL
, then only then item gets pushed into the collection (tb.ItemsSource as IList).Add(item);
Kindly assist me, how to assign the Value in a Null-able IEnumerable
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…