Exception thrown when trying to disable a control
I have a Ribbon CheckBox and a Ribbon RadioButton. When CheckBox is checked, the RadioButton will be disa开发者_C百科ble and grayed out. This supposed to be very easy (see following code), but when the program compile, it kept giving an error:
"Object reference not set to an instance of an object."
Which I don't quite understand. Following is my code:
<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
}
As your control is loaded, the CheckBox is created first, then the RadioButton. Likely the event is hooked up earlier than your radioButton1 is set. You can verify this by removing the IsChecked=true from the XAML temporarily.
A couple of options here:
Data Binding - use the IsChecked property to automatically update your radio button without code. You'll need to name your checkbox.
IsEnabled="{Binding IsChecked, ElementName=checkBox1, Mode=OneWay}"
Check for null in your existing code -
if (radioButton1 != null) { radioButton1.IsEnabled = false; }
Updated your radioButton state after the Loaded event has completed.
private bool isLoaded;
protected override OnLoaded(...) { this.isLoaded = true; }
private void CheckBox1_Checked(object sender, RoutedEventArgs e) { if (this.isLoaded) { radioButton1.IsEnabled = false; // this is where exception is thrown } }
The preferred method is generally #1.
精彩评论