WPF-隐藏组合框选择

时间:2019-08-02 09:08:42

标签: c# wpf xaml

我有一个组合框,允许用户从图像集中进行选择。由于图像的大小,一旦选择了图像,我不想在组合框中显示该图像。我只是希望选择一个项目时,组合框中什么也不显示。

到目前为止,我已经尝试在用户进行选择后将selectedImageSource设置为1时将selectedImageIndex设置为-1,但是由于默认情况下仍在组合框中显示[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);

        }
    }

1 个答案:

答案 0 :(得分:0)

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

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

Can I use a different Template for the selected item in a WPF ComboBox than for the items in the dropdown part?

我希望这会有所帮助!

相关问题