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

时间:2017-02-01 20:03:03

标签: c# wpf eventargs routedeventargs

我有一个按钮,应显示一些内容如果 name_checked返回 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

  

我想要的是:如果布尔name_checked返回false,则停止按钮操作如果布尔返回false,我根本不想显示任何消息,甚至是错误

  • 所以使用它是否正确? 。如果没有,请告诉我正确的方法。

2 个答案:

答案 0 :(得分:1)

在ViewModel(CodeBehind)中设置一个bool

public bool OkToContinue { get; set; }  

然后在XAML中执行此操作:

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

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

答案 1 :(得分:0)

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

private string message = "Unknown";

以便没有空指针。 string.Empty也可以正常运作。