首页 > 解决方案 > WPF - 隐藏组合框选择

问题描述

我有一个组合框,允许用户从一组图像中进行选择。由于图像的大小,一旦选择了图像,我不想在组合框中显示图像。选择项目时,我只是想在Combobox中显示任何内容。

到目前为止,我已经尝试将 selectedImageIndex 设置为 -1,一旦在用户进行选择时设置了 selectedImageSource,但这不起作用,因为默认情况下,[0] 处的第一个图像仍显示在组合框中。我正在使用 MVVM。

XAML

<ComboBox Grid.Row="1" SelectedIndex="{Binding SelectedImageIndex}" ItemsSource="{Binding SymbolImageCollection}">
                            <ComboBox.ItemTemplate>
                                <DataTemplate>
                                        <Image Source="{Binding Img}" Width="50" Height="50"/>
                                </DataTemplate>
                            </ComboBox.ItemTemplate>
                            <ComboBox.ItemsPanel>
                                <ItemsPanelTemplate>
                                    <WrapPanel Width="300" HorizontalAlignment="Left"/>
                                </ItemsPanelTemplate>
                            </ComboBox.ItemsPanel>
                        </ComboBox>

查看模型

public ObservableCollection<SymbolImage> SymbolImageCollection { get { return AppearanceLayerProperties.Instance.SymbolImageCollection; } }

    private string _selectedImageSource;
    public string SelectedImageSource
    {
        get { return _selectedImageSource; }
        set
        {
            SetProperty(ref _selectedImageSource, value);
            //SelectedImageIndex = -1;
        }
    }

    private int _selectedImageIndex;
    public int SelectedImageIndex
    {
        get { return _selectedImageIndex; }
        set
        {
            var selectedImage = AppearanceLayerProperties.Instance.SymbolImageCollection[value].ImgSource;
            SelectedImageSource = selectedImage;
            SetProperty(ref _selectedImageIndex, -1);

        }
    }

标签: c#wpfxaml

解决方案


在选择 ComboBox 的一个项目后将选择更改回 null 不是一个好习惯,因为如果您需要使用选定的值,它不再可用。

一种解决方案可能是为 ComboBox 的选定项目使用不同的模板。这样,您可以删除图像,但在其位置放置其他内容,例如文本,以便用户了解选择了什么项目。这是以前的 StackOverflow 帖子,解释了如何执行此操作:

我可以为 WPF ComboBox 中的选定项目使用与下拉部分中的项目不同的模板吗?

我希望这有帮助!


推荐阅读