我在班级
中创建了可观察的集合public ObservableCollection<NewsTags> NewsTagsList { get; private set; }
public RelayCommand RefreshNewsTags
{
get
{
return _refreshNewsTagsCommand ?? (
_refreshNewsTagsCommand = new RelayCommand(
async () => {
var list = await _newsTagsService.GetAllAsync(1, false);
foreach (var item in list)
{
NewsTagsList.Add(item);
}
}
));
}
}
并致电自定义控件
<tagsListSelector:BoxSelector Items="{Binding NewsTagsList}" />
和boxselector.cs
public partial class BoxSelector : ContentView
{
public BoxSelector()
{
InitializeComponent();
}
public static readonly BindableProperty ItemsProperty =
BindableProperty.Create<BoxSelector, IEnumerable>(
view => view.ItemsSource,
null,
propertyChanged: (bindableObject, oldValue, newValue) => {
((BoxSelector)bindableObject).ItemsSourceChanged(bindableObject, oldValue, newValue);
}
);
private void ItemsSourceChanged(BindableObject bindableObject, IEnumerable oldvalue, IEnumerable newvalue)
{
boxSelectorGrid.Children.Clear();
foreach (object obj in newvalue)
{
boxSelectorGrid.Children.Add(new Label { Text="LOL", TextColor= Color.FromHex("#000")});
}
}
但没有变化。 p.s in newslist.cs NewsTagsList.Count == 10但在BoxSelector == 0
我做错了什么?
答案 0 :(得分:1)
在ItemsSourceChanged方法中,如果newValue的类型为INotifyCollectionChanged,则需要连接CollectionChanged事件,并在CollectionChanged代码内部执行集合更改时要执行的操作。如果类型为INotifyCollectionChanged,您还需要取消订阅oldValue上的事件。
这样的事情:
private void ItemsSourceChanged(BindableObject bindableObject, IEnumerable oldvalue, IEnumerable newvalue)
{
var incc = oldvalue as INotifyCollectionChanged;
if (incc != null)
{
incc.CollectionChanged -= Incc_CollectionChanged;
}
incc = newvalue as INotifyCollectionChanged;
if (incc != null)
{
incc.CollectionChanged += Incc_CollectionChanged;
}
boxSelectorGrid.Children.Clear();
foreach (object obj in newvalue)
{
boxSelectorGrid.Children.Add(new Label { Text = "LOL", TextColor = Color.FromHex("#000") });
}
}
private void Incc_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
// handle Added rows
break;
case NotifyCollectionChangedAction.Remove:
// handle deleting rows
break;
case NotifyCollectionChangedAction.Move:
// handle moving rows
break;
case NotifyCollectionChangedAction.Replace:
// handle replacing rows
break;
case NotifyCollectionChangedAction.Reset:
// reload everything
break;
}
}