我有一个ObservableCollection
调用Collection1,我想通过转换器绑定到ListBox
的ItemsSource
。使用Converter时,CollectionChanged事件未注册?
当我指定一个转换器时,绑定不起作用 - 它只使用转换器进行初始化,而不再使用转换器。
当我做不是指定一个转换器,绑定工作,但用户控件不能正确显示,因为它不明白。
我了解到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.
如果有人可以帮助我将不胜感激。谢谢!
这是我对这个问题的解决方案,根据下面的其他评论。
我不是通过转换器进行绑定,而是在类中为绑定创建了一个ObservableCollection属性,然后在代码中手动订阅了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}" />
这似乎工作得很好。
我明白了,所以CollectionChanged必须在Converter返回时注册?那很有意思。它所做的只是将一个类型的集合转换为另一个类型的集合。 – dythim 2011-03-18 02:10:31
@dythim:这是错误的做法。事先将集合转换为一个'ObservableCollection'并直接绑定到那个。 –
Jon
2011-03-18 02:15:42
@Jon:谢谢。我会考虑以这种方式重构它。 – dythim 2011-03-18 02:20:22