为什么未在DataGrid中更新ItemsSource
本文关键字:更新 ItemsSource DataGrid 为什么 | 更新日期: 2023-09-27 17:57:40
我的窗口使用MyUserControl
,并通过MyItemsProperty
属性向其传递一组项。MyUserControl
将项转换为MyClassBag
,并将项添加到绑定到DataGrid
的ItemsSource的WrappedItems
集合(OnMyItemsChanged->CollectionChanged->AddItem)。
问题是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(...));
}
}
窗口.xaml
<uc:MyUserControl MyItems="{Binding ItemsForMyUserControl}" />
我不久前也遇到了类似的问题。
请使MyClass
类继承自Freezable
类,一切都可以工作。如果有帮助,请告诉我。