我的窗口使用 MyUserControl并通过 MyItemsProperty 将项目集合传递给它属性(property)。 MyUserControl将项目转换为 MyClassBag并将项目添加到 WrappedItems集合 (OnMyItemsChanged->CollectionChanged->AddItem) 绑定(bind)到 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}" /> 

请您参考如下方法:

我前段时间遇到过类似的问题。

请使 MyClass 类继承自 Freezable 类,一切都可以正常工作。如果有帮助,请告诉我。


评论关闭
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

C# Excel 自动化仅在 Excel 可见时起作用