WPF:带有重置项目的组合框 [英] WPF: ComboBox with reset item

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

问题描述

我想在WPF中创建一个组合框,该组合框的顶部有一个 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代码或附加行为来完成,因为我真的不喜欢为View更改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>
[...]

我认为最好的方法是以某种方式添加设置<$ c $的事件触发器c> 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:带有重置项目的组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆