我的窗口使用MyUserControl
并通过MyItemsProperty
属性向其传递一组项目。 MyUserControl
会将项目转换为MyClassBag
,并将项目添加到WrappedItems
集合(OnMyItemsChanged-> CollectionChanged-> AddItem),该集合绑定到DataGrid
的ItemsSource。
问题是ItemsSource没有更新(我在control.WrappedItems.Add(new MyClassBag { ... });
设置制动点,它确实到了那里)。
但是,如果我在MyUserControl
内放置一个按钮并通过按钮的click方法添加项目(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}" />
答案 0 :(得分:0)
前段时间我遇到过类似的问题。
请让MyClass
类继承自Freezable
类,一切都可行。如果有帮助,请告诉我。