How to put a predetermined text in a ComboBox?

1

I have the following comboBox

    <ComboBox x:Name="cmbBuscarPor" HorizontalAlignment="Left" Text="Buscar por " Margin="210,10,0,0" VerticalAlignment="Top" Width="120" Height="30" VerticalContentAlignment="Center">
        <ComboBoxItem Content="Nombre" HorizontalContentAlignment="Center"/>
        <ComboBoxItem Content="Apellido paterno" HorizontalContentAlignment="Center"/>
        <ComboBoxItem Content="Puesto" HorizontalContentAlignment="Center"/>
    </ComboBox>

I want to put a text that appears at the beginning that is not any of the options that are already predetermined

    
asked by Richard Yordy 10.04.2018 в 23:28
source

1 answer

1

The easiest way is to use CompositeCollection to merge text and default data from the database directly into ComboBox, for example:

<ComboBox x:Name="cmbBuscarPor" SelectedIndex="0">
    <ComboBox.ItemsSource>
        <CompositeCollection>
            <ComboBoxItem Visibility="Collapsed">-- Seleccionar item --</ComboBoxItem>
            <CollectionContainer Collection="{Binding Source={StaticResource ResourceKey=MyComboOptions}}"/>
        </CompositeCollection>
    </ComboBox.ItemsSource>
</ComboBox>

And in Resources define StaticResource to link the options of ComboBox to its DataContext , because the direct link in CollectionContainer does not work correctly.

<Window.Resources>
    <CollectionViewSource Source="{Binding}" x:Key="MyComboOptions" />
</Window.Resources>

In this way, you can define your ComboBox options only in xaml, for example

   <ComboBox x:Name="cmbBuscarPor" SelectedIndex="0">
        <ComboBox.ItemsSource>
            <CompositeCollection>
                <ComboBoxItem Visibility="Collapsed">-- Seleccionar item --</ComboBoxItem>
                <ComboBoxItem >Opction 1</ComboBoxItem>
                <ComboBoxItem >Opcion 2</ComboBoxItem>
            </CompositeCollection>
        </ComboBox.ItemsSource>
    </ComboBox>

Other Form:

<ComboBox SelectedIndex="0">
    <ComboBox.ItemsSource>
        <CompositeCollection>
            <ListBoxItem>Seleccione una Opción</ListBoxItem>
            <CollectionContainer Collection="{Binding Source={StaticResource TUDATASOURCE}}" />
        </CompositeCollection>
    </ComboBox.ItemsSource>
</ComboBox>

Or of this menera:

<ComboBox Name="MyComboBox"
 IsEditable="True"
 IsReadOnly="True"
 Text="-- Seleccionar Item --" />

Obviously you will have to add your other options, but this is probably the easiest way to do it.

However, there is a drawback in this method, which is when the text inside your ComboBox will not be editable, it is still selectable. However, given the low quality and complexity of each alternative that I have found to date, this is probably the best option.

    
answered by 10.04.2018 / 23:39
source