c# - 使用 Converter 时未注册 CollectionChanged 事件?

标签 c# wpf observablecollection

我有一个名为 Collection1 的 ObservableCollection,我想通过转换器将其绑定(bind)到 ListBoxItemsSource

当我指定一个转换器时,绑定(bind)不起作用——它只使用转换器进行初始化,再也不会。

当我指定转换器时,绑定(bind)有效,但用户控件无法正确显示,因为它不理解。

我了解到 CollectionChanged 事件处理程序不是在指定转换器时设置的,而是在未指定转换器时设置的。我不知道为什么会这样。

总结:

有效:

<ListBox Name="theListBox" 
         Margin="8,28,8,8"
         ItemsSource="{Binding Collection1, Converter={StaticResource myConverter}}"
         ItemContainerStyle="{DynamicResource ContainerStyle}" /> 

Collection1.CollectionChanged is null.

确实有效:

<ListBox Name="theListBox" 
         Margin="8,28,8,8"
         ItemsSource="{Binding Collection1}"
         ItemContainerStyle="{DynamicResource ContainerStyle}" /> 

Collection1.CollectionChanged is not null.

如果有人能提供帮助,我将不胜感激。谢谢!


根据下面的其他评论,这是我对这个问题的解决方案。

我没有通过转换器进行绑定(bind),而是在类中创建了一个 ObservableCollection 属性用于绑定(bind),然后在代码中手动订阅了 Collection1.CollectionChanged 事件。

public partial class MyScreen : UserControl
{
    public ObservableCollection<Class2> BindingCollection { get; set; }  // <-- Bind to this

    public MyScreen()
    {
        this.InitializeComponent();

        BindingCollection = new ObservableCollection<Class2>();

        Collection1.CollectionChanged += new NotifyCollectionChangedEventHandler(Collection1_CollectionChanged);
        MediViewData.Instance.ActivePatientCareReport.PropertyChanged += new PropertyChangedEventHandler(ActivePatientCareReport_PropertyChanged);

    }

    void Collection1_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        BindingCollection.Clear();

        foreach (var c1 in Collection1)
        {
            var c2 = ConvertClass1ToClass2(c1);
            if (c2 != null) BindingCollection.Add(c2);
        }
    }
}

XAML 类似于:

<ListBox x:Name="MyListBox" 
         Margin="8,28,8,8"
         ItemContainerStyle="{DynamicResource ContainerStyle}" 
         ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=BindingCollection}" />

这似乎工作得很好。

最佳答案

ItemsControl.ItemsSource 具有连接到 CollectionChanged 事件并相应地更新其 Items 集合的逻辑。除非您从转换器返回相同的 ObservableCollection 实例,否则 CollectionChanged 通知无法通过转换器从 Binding 自动传播。

精确的修复将取决于转换器中发生的事情。

更新

尝试使用原始的 ObservableCollection 而不是将集合从一种泛型类型转换为另一种类型,而是更改转换器以转换单个项目并通过在控件的 ItemTemplate 中使用它来将其应用于每个项目。

关于c# - 使用 Converter 时未注册 CollectionChanged 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5347184/

相关文章:

c# - WPF Datagrid Double Click Cell MVVM设计

c# - MVVM 选项卡 : Focus new tab

wpf - 如何复制可观察的集合

c# - 检查列表中的间隔是否等长

C# Double.ToString()

c# - 如何获得超过 2 个内核的 CPU 使用率?

c# - yield 返回多少?

c# - 如何将此 WPF 控件添加到我的 WinForm 中?

c# - 将 ViewModel 添加为 app.xaml 中的资源是一种好习惯吗?

xaml - 有没有比在 XAML 中使用 ObservableCollection 进行快速绑定(bind)更好的方法?