复选框无法在xaml中设置初始值?

时间:2012-07-10 16:06:08

标签: silverlight silverlight-4.0 silverlight-5.0

在xaml中将代码设为:

<CheckBox x:Name="cbxNew" Content="New" IsChecked="true"  Checked="cbxNew_Checked"  />

private void cbxNew_Checked(object sender, RoutedEventArgs e)
        {
            this.txtTest.Text = "";
        }

然后运行应用程序并收到错误:

Set Property
System.Windows.Controls.Primitives.ToggleButton.IsChecked threw an exception
很惊讶。如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

出现问题的原因是Checked事件在对话框/页面的InitializeComponent()期间触发,但在txtTest被赋值之前。

只需将代码更改为

即可
private void cbxNew_Checked( object sender, RoutedEventArgs e )
{
  if ( this.txtTest != null )
    this.txtTest.Text = "";
}