如果特定值为 false,则阻止 wpf 按钮运行

prevent wpf button from functioning if a specific value is false

我有一个应该显示一些内容的按钮 If 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" />

└─ 输出错误: (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

更改 message 以在不是 Josh 时显示默认值。如:

private string message = "Unknown";

以免出现空指针。 string.Empty 也可以。

在您的 ViewModel(代码隐藏)中设置一个布尔值

public bool OkToContinue { get; set; }  

然后在 XAML 中执行此操作:

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

当 OkToContinue==false 时按钮将被禁用,否则将被启用。