我有一个功能区复选框和一个功能区单选按钮。当 CheckBox 被选中时,RadioButton 将被禁用并变灰。这本来应该很简单(见下面的代码),但是当程序编译时,它一直报错:
“未将对象引用设置为对象的实例。”
我不太明白。以下是我的代码:
<ribbon:RibbonCheckBox Unchecked="CheckBox1_Unchecked"
Checked="CheckBox1_Checked" IsChecked="True"
Label="Foo" />
<ribbon:RibbonRadioButton x:Name="radioButton1" Label="=Santa" />
private void CheckBox1_Checked(object sender, RoutedEventArgs e)
{
radioButton1.IsEnabled = false; // this is where exception is thrown
}
最佳答案
加载控件时,首先创建 CheckBox,然后创建 RadioButton。事件可能在设置 radioButton1 之前就已连接。您可以通过暂时从 XAML 中删除 IsChecked=true 来验证这一点。
这里有几个选项:
数据绑定(bind) - 使用 IsChecked 属性自动更新单选按钮,无需代码。您需要为您的复选框命名。
IsEnabled="{Binding IsChecked, ElementName=checkBox1, Mode=OneWay}"
检查现有代码中是否存在 null -
if (radioButton1 != null) { radioButton1.IsEnabled = false; }
在 Loaded 事件完成后更新了 radioButton 状态。
私有(private) bool 已加载;
protected 覆盖 OnLoaded(...) { this.isLoaded = true; }
private void CheckBox1_Checked(对象发送者, RoutedEventArgs e) { if (this.isLoaded) { radioButton1.IsEnabled = false;//这是抛出异常的地方 } }
首选方法通常是#1。
关于c# - 尝试禁用控件时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6813700/