我的窗口使用
问题在于ItemsSource未更新(我在
MyUserControl
并通过MyItemsProperty
属性向其传递一个项目集合。MyUserControl
将项目转换为MyClassBag
并将其添加到WrappedItems
集合(OnMyItemsChanged -> CollectionChanged -> AddItem),该集合绑定到DataGrid
的ItemsSource。问题在于ItemsSource未更新(我在
control.WrappedItems.Add(new MyClassBag { ... });
上设置了断点,但它确实到达)。但是,如果我在MyUserControl
中放置一个按钮并通过按钮的单击方法添加项(WrappedItems.Add(new MyClassBag { ... });
),则ItemsSource会得到更新。问题出在哪里?public partial class MyUserControl : UserControl
{
public static readonly DependencyProperty MyItemsProperty =
DependencyProperty.Register("MyItems",
typeof(ObservableCollection<MyClass>),
typeof(MyUserControl),
new PropertyMetadata(
new ObservableCollection<MyClass>(),
new PropertyChangedCallback(OnMyItemsChanged)
)
);
public ObservableCollection<MyClass> MyItems
{
get { return (ObservableCollection<MyItems>)GetValue(MyItemsProperty); }
set { SetValue(MyItemsProperty, value); }
}
private static void OnMyItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
control = d as MyUserControl;
var items = e.NewValue as ObservableCollection<MyClass>;
states.CollectionChanged += new NotifyCollectionChangedEventHandler(CollectionChanged);
AddItem(control, items);
}
private static void CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
var items = sender as ObservableCollection<MyClass>;
if (e.Action == NotifyCollectionChangedAction.Add)
{
control.AddNewItem();
}
}
public ObservableCollection<MyClassBag> WrappedItems { get; set; }
public void AddNewItem()
{
WrappedItems.Add(new MyClassBag { ... });
}
private void Button_Click(object sender, RoutedEventArgs e)
{
AddNewItem();
}
}
MyUserControl.XAML
<DataGrid ItemsSource="{Binding WrappedItems ... />
<Button Click="Button_Click" />
Window.cs
public partial class Window1 : Window
{
public ObservableCollection<MyClass> ItemsForMyUserControl { get; set; }
private void Load()
{
ItemsForMyUserControl.Add(new MyClass(...));
ItemsForMyUserControl.Add(new MyClass(...));
}
}
Window.xaml
<uc:MyUserControl MyItems="{Binding ItemsForMyUserControl}" />
Button_Click
调用AddNewItem
方法时,ItemsSource会更新,我可以在DataGrid
中看到该项。但是当它从CollectionChanged(control.AddNewItem();)调用时,该项被添加到WrappedItems
,但我在DataGrid
中看不到它。 - theateist