-2

Is there a way to disable a button until 2 textboxes and 2 comboboxes are filled and selected? I've tried to search it, but nothing that I find does that.

Z3RP
  • 328
  • 1
  • 16
GizaRex
  • 1
  • 2

2 Answers2

2

Try this:

C#:

public MainWindow()
{
    InitializeComponent();
    btnSubmit.IsEnabled = false;
    txtFirstName.TextChanged += Program_MyEvent;
    txtSurName.TextChanged += Program_MyEvent;
    cboFruits.SelectionChanged += Program_MyEvent;
    cboSports.SelectionChanged += Program_MyEvent;
}

void Program_MyEvent(object sender, EventArgs e)
{
    if (txtFirstName.Text.Length > 0 && txtSurName.Text.Length > 0 && cboFruits.SelectedIndex >= 0 && cboSports.SelectedIndex >= 0)
    {
        btnSubmit.IsEnabled = true;
    }
    else
    {
        btnSubmit.IsEnabled = false;
    }
}

XAML:

<TextBox x:Name="txtFirstName" HorizontalAlignment="Left" Height="23" Margin="70,96,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="txtSurName" HorizontalAlignment="Left" Height="23" Margin="70,124,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
<ComboBox Name="cboFruits" HorizontalAlignment="Left" Height="100" Margin="419,75,0,0" VerticalAlignment="Top" Width="100">
    <System:String>Apple</System:String>
    <System:String>Grapes</System:String>
    <System:String>Banana</System:String>
</ComboBox>
<ComboBox Name="cboSports"  HorizontalAlignment="Left" Height="100" Margin="419,237,0,0" VerticalAlignment="Top" Width="100">
    <System:String>Football</System:String>
    <System:String>Basketball</System:String>
    <System:String>Tennis</System:String>
</ComboBox>
<Button Name="btnSubmit" Content="Button" HorizontalAlignment="Left" Margin="582,224,0,0" VerticalAlignment="Top" Width="75"/>

@Çöđěxěŕ is right the MVVM framework is worth looking into.

Dev
  • 1,780
  • 3
  • 18
  • 46
0

Perhaps look at Text Box Text Changed event in WPF for textbox and ComboBox- SelectionChanged event has old value, not new value for combo.

Both of these will use events that fire on change and will you to create a function that can check the states of the controls and enable/disable the button accordingly.

Robert Pilcher
  • 376
  • 1
  • 10