为什么 DataGrid 中的 ItemsSource 没有更新

3
我的窗口使用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}" />

在添加控件后,再次在代码中绑定网格,看看是否解决了您的问题。这只是一个快速提示,在我试验之前。 - voddy
@voddy,你是指再次绑定网格视图吗? - theateist
你的 MyClassBag 继承了 INotifyPropertyChanged 接口吗? - voddy
@voddy,为了解释这个问题,我稍微简化了代码:当我从Button_Click调用AddNewItem方法时,ItemsSource会更新,我可以在DataGrid中看到该项。但是当它从CollectionChanged(control.AddNewItem();)调用时,该项被添加到WrappedItems,但我在DataGrid中看不到它。 - theateist
好的,我明白了。您可以尝试在添加控件后设置网格的数据上下文。例如:YourdataGrid.DataContext = WrappedItems; - voddy
显示剩余10条评论
1个回答

0

我之前遇到过类似的问题。

请让 MyClass 类继承自 Freezable 类,这样可能会解决问题。如果有帮助,请告诉我。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接