【问题标题】:Combine CollectionViewSource with CompositeCollection in XAML在 XAML 中将 CollectionViewSource 与 CompositeCollection 结合使用
【发布时间】:2018-03-08 09:18:04
【问题描述】:

我的ComboBox 有一个CollectionViewSource。现在我想向集合中添加一个“空元素”或“空元素”。赋予使用取消选择当前选择的能力。

通常,我会为此任务使用CompositeCollection (like this),因为我不想在我的 ViewModel 或代码隐藏 (.xaml.cs) 中处理此类事情。

这里是相关代码sn-ps:

<UserControl.Resources>
    <CollectionViewSource x:Key="FooItemsCollection" Source="{Binding FooItems}">
        <CollectionViewSource.SortDescriptions>
            <scm:SortDescription PropertyName="Name" />
        </CollectionViewSource.SortDescriptions>
     </CollectionViewSource>
</UserControl.Resources>

<ComboBox SelectedItem="{Binding SelectedFooItem, Mode=TwoWay}" 
          ItemsSource="{Binding Source={StaticResource FooItemsCollection}}"
          IsSynchronizedWithCurrentItem="False"
          DisplayMemberPath="Name" />

有什么好的解决办法吗?

EDIT 选择此空元素时,SelectedFooItem 必须设置为空。

【问题讨论】:

  • 如果我理解正确的话,你的空元素应该基本上是一个平面按钮。如果它可以帮助你,请检查它stackoverflow.com/questions/44564928/…
  • @DanieleSartori 这将导致绑定错误,在视图中由红色边框指示。 SelectedFooItem 的二传手也不会命中。我已经编辑了我的问题。
  • 您可以使用选择更改事件。如果所选项目不是“FooItem”类型,则将所选项目设置为空,而不是添加按钮,而是添加一个包含文本块的假组合框项目
  • @DanieleSartori 引用我自己的话:“我不想在我的 ViewModel 或代码隐藏中处理这些事情”。我不敢相信这样的事情没有基于 xaml 的解决方案。

标签: c# wpf mvvm combobox


【解决方案1】:

试试这个

        <ComboBox SelectedItem="{Binding SelectedFooItem, Mode=TwoWay}" 
  IsSynchronizedWithCurrentItem="False"
  DisplayMemberPath="Name" >
            <ComboBox.ItemsSource>
                    <CompositeCollection>
                        <CollectionContainer Collection="{Binding Source={StaticResource FooItemsCollection}}" />
                        <ComboBoxItem>
                            <TextBlock Content="NotAFoo"></Button>
                        </ComboBoxItem>
                    </CompositeCollection>
            </ComboBox.ItemsSource>
            <ComboBox.Style>
                <Style TargetType="{x:Type ComboBox}">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Path=SelectedItem.Content}" Value="NotAFoo">
                            <Setter Property="SelectedItem" Value="{x:Null}" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </ComboBox.Style>
        </ComboBox>

检查这是否有效。我现在没有时间搭建测试环境,如果你在你的应用中尝试它肯定会更快。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    • 2020-06-24
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多