axcelenator
axcelenator

Reputation: 1527

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

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;

        } 

Upvotes: 0

Views: 410

Answers (1)

cyberj0g
cyberj0g

Reputation: 3787

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.

Upvotes: 1

Related Questions