Search code examples
c#wpfeventargsroutedeventargs

prevent wpf button from functioning if a specific value is false


i have a button that should show some content If the name_checked return true

• C# :

private bool name_checked    = false;  // <<--------#

private string username      = "Smith"; 
private string message       =   null; 

public MainWindow() {           

     if (username == "Josh"){ 
         name_checked = true; // <<--------# if right true
         message      =  "Welcome Josh";        
} 

private void button__Click(object sender, RoutedEventArgs e) {  

    if ( name_checked == true ) MessageBox.Show(message);
}

• wpf xaml :

<Button Name="anyname" Click="button__Click"  
Width="100" Height="50" HorizontalAlignment="Right" 
Margin="0,4,154,0" VerticalAlignment="Top" Grid.Row="2" Grid.RowSpan="2" />

└─ output Error : (InvalidOperationExction was unhandled)

What i want is : to stop the Button from acting if the the Boolean name_checked return false
i dont want any message to show at all if the Boolean return false , even Errors

  • so am using it correct or not ?? . if not please show me the right way.

Solution

  • Set a bool in your ViewModel (CodeBehind)

    public bool OkToContinue { get; set; }  
    

    Then in the XAML do this:

    <Button IsEnabled="{Binding OkToContinue}"  Click="ButtonBase_OnClick" />
    

    When OkToContinue==false the button will be disabled, otherwise it will be Enabled.