带有重置项的组合框

带有重置项的组合框

本文介绍了WPF:带有重置项的组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 WPF 中创建一个 ComboBox,顶部有一个 null 项目,当它被选中时,SelectedItem 应设置为 null(重置为默认状态).我一直在寻找,但没有找到令人满意的解决方案.

I want to make a ComboBox in WPF that has one null item on the top, when this gets selected, the SelectedItem should be set to null (reset to default state). I've searched like forever, but didn't find a solution that was satisfying.

如果可能,我希望它只使用 XAML 代码或附加的行为来完成,因为我真的不喜欢更改 ViewModel 中的内容或覆盖标准控件.

If possible I would want it to do it only with XAML code or an attached behaviour, because I don't really like changing stuff in the ViewModel for the View, or overriding standard controls.

这是我到目前为止想出的(缩短的代码):

Here is what I've come up with so far (shortened code):

[...]
<Popup x:Name="PART_Popup" [...]>
    <Border x:Name="PopupBorder" [...]>
        <ScrollViewer x:Name="DropDownScrollViewer" [...]>
            <StackPanel [...]>
                <ComboBoxItem>(None)</ComboBoxItem>
                <ItemsPresenter x:Name="ItemsPresenter"/>
            </StackPanel>
        </ScrollViewer>
    </Border>
</Popup>
[...]

我认为最好的方法是以某种方式添加一个事件触发器,在项目被选中时将 SelectedIndex 设置为 -1,但这里是我的地方卡住了.

I think the best way would be to somehow add an event trigger that sets the SelectedIndex to -1 when the item gets selected, but here is where I've got stuck.

任何想法如何做到这一点?或者更好的方式,比如附加行为?

Any ideas how to do this? Or an better way, like an attached behaviour?

推荐答案

考虑实施 空对象模式对于无"组合框项目,并将此项目添加到您的项目列表中.然后实现自定义逻辑以在该类中保存空对象,或者只检查所选项目是否为 NullItem 类型.

Think about implementing a Null Object Pattern for the "None" combobox item and add this item to your items list. Then implement custom logic for saving null object in that class, or just check if selected item is of NullItem type.

这篇关于WPF:带有重置项的组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 02:27