将空项添加到有界组合框中

Lam*_*fif 3 .net c# wpf mvvm model-binding

我需要在wpf mvvm应用程序中的有界组合框中添加一个空项目,我试过这个

<ComboBox TabIndex="23"  Text="{Binding Specialisation}" DisplayMemberPath="refsp_libelle">
      <ComboBox.ItemsSource>
                          <CompositeCollection >
                                        <ComboBoxItem  > </ComboBoxItem>
                                        <CollectionContainer  Collection="{Binding SpecialisationItemSource}" ></CollectionContainer>
                       </CompositeCollection>

     </ComboBox.ItemsSource>
  </ComboBox>
Run Code Online (Sandbox Code Playgroud)

它在我尝试添加空项目之前有效.

<ComboBox TabIndex="23" Text="{Binding Specialisation}" ItemsSource="{Binding SpecialisationItemSource}" DisplayMemberPath="refsp_libelle"/>
Run Code Online (Sandbox Code Playgroud)

所以我需要知道:

  1. 我犯的错误是什么?
  2. 我该如何解决?

谢谢,

Grx*_*x70 5

为什么你的方法不起作用?

你使用{Binding SpecialisationItemSource}哪个,因为没有明确定义绑定的来源,回到使用目标DataContext作为源 - 或者更确切地说,如果CollectionContainer是a FrameworkElement,它就不是.因此,绑定的来源是,null并且组合中没有项目显示.您需要Source明确设置绑定的属性以使其工作(设置RelativeSourceElementName不工作).

其实即使 CollectionContainer FrameworkElement 它仍然是行不通的,因为 CompositeCollection 不是 FrameworkElement (它甚至不是一个 DependencyObject ),所以数据文脉传承将被打破).

怎么解决?

为了使用"隐式绑定",您可以CollectionViewSource在资源字典中放置一个,并使用它来使用StaticResource扩展名来填充集合容器:

<ComboBox>
    <ComboBox.Resources>
        <CollectionViewSource x:Key="Items" Source="{Binding SpecialisationItemSource}" />
    </ComboBox.Resources>
    <ComboBox.ItemsSource>
        <CompositeCollection>
            <TextBlock />
            <CollectionContainer Collection="{Binding Source={StaticResource Items}}" />
        </CompositeCollection>
    </ComboBox.ItemsSource>
</ComboBox>
Run Code Online (Sandbox Code Playgroud)

请注意,我使用Collection="{Binding Source={StaticResource Items}}"的不仅仅是Collection="{StaticResource Items}"- 因为类型的对象CollectionViewSource不是实际的集合,并且不是CollectionContainer.Collection属性的有效值,并且绑定机制旨在将其转换为实际集合.另外,我用空替换了ComboBoxItem一个空TextBlock,因为前者导致绑定错误,我真的不喜欢看到.最终,我甚至会用绑定集合的项目类型的默认值替换它.