Combo Box 1st item is remained empty in WPF c#

366 views Asked by At

I have a combox in my wpf and 2 items called:

  1. Send
  2. Receive.

I want to make the combobox to show a general message(send/receive) when the WPF is loaded up at first time. I tried to apply a string to the Text property in the XAML but it didn't work:

<ComboBox x:Name="opBox" HorizontalAlignment="Left" Text="Send/Receive"/> 

Is there any way to apply this text so it won't be as an item?

In addition, when one of the items is selected I'm hiding or making visible the appropriate button by an event called SelectionChanged. But if again the user selects the general message send/receive I want the 2 buttons hide together. When I try to do that in the SelectionChanged I got some errors.

Update: Here is my SelectionChanged event:

private void opBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

        if (opBox.SelectedIndex == 1)//Send
        {

            mySendButton.Visibility = Visibility.Visible;
            myReceiveButton.Visibility = Visibility.Hidden;
        }
        else if(opBox.SelectedIndex==2)//Receive
        {

            mySendButton.Visibility = Visibility.Hidden;
            myReceiveButton.Visibility = Visibility.Visible;
            ClearTextBox();
        }
        else if (opBox.SelectedIndex == 0)//Send or Receive
        {

                mySendButton.Visibility = Visibility.Hidden;
                myReceiveButton.Visibility = Visibility.Hidden;

        } 
1

There are 1 answers

2
cyberj0g On BEST ANSWER

Try setting IsEditable and IsReadonly properties, like that:

<ComboBox x:Name="opBox" IsEditable="True" IsReadOnly="True" HorizontalAlignment="Left" Text="Send/Receive"/>

To stop your code from crashing on InitializeComponent() add the following code on top of opBox_SelectionChanged

if (mySendButton==null||myReceiveButton==null)
    return;

Also note that directly managing controls properties from event handlers is not WPF way. It's better to use data binding and view model-based approaches to customize WPF UI behavior.