The Doctor
The Doctor

Reputation: 693

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

Upvotes: 0

Views: 463

Answers (2)

Kelly
Kelly

Reputation: 7183

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.

Upvotes: 1

ΩmegaMan
ΩmegaMan

Reputation: 31616

Change message to show a default when it is not Josh. Such as:

private string message = "Unknown";

So as to not have a null pointer. string.Empty could work as well.

Upvotes: 0

Related Questions